以下是一个按顺序循环使用Promise加载图像的示例代码:
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error('Failed to load image'));
img.src = url;
});
}
function loadImagesSequentially(imageUrls) {
const loadImagePromises = imageUrls.map(url => () => loadImage(url));
const sequentiallyLoadImages = loadImagePromises.reduce(
(chain, loadImagePromise) => chain.then(loadImagePromise),
Promise.resolve()
);
return sequentiallyLoadImages;
}
const imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
];
loadImagesSequentially(imageUrls)
.then(images => {
// 所有图像已成功加载
console.log(images);
})
.catch(error => {
// 加载过程中出现错误
console.error(error);
});
上述代码中的loadImage
函数用于创建一个Promise来加载单个图像。loadImagesSequentially
函数接受一个图像URL数组,并将每个URL转换为一个加载图像的Promise。然后,它使用reduce
方法将这些Promise链接在一起,以确保它们按顺序加载图像。最后,loadImagesSequentially
返回一个Promise,用于在所有图像成功加载后进行处理。
在使用示例中,imageUrls
数组包含了要加载的图像URL。loadImagesSequentially
函数将这些URL作为参数,并返回一个Promise。在Promise解析后,它将返回一个包含所有成功加载图像的数组。如果在加载过程中发生错误,则Promise将被拒绝,并将错误传递给catch
方法进行处理。