我有一个图像数组,我想做的是使用异步函数通过图像处理库处理所有这些图像。
我的代码可以正常工作,因为数组中的每个图像都有一个名为index的字段,它表示它在数组中的位置。
// Adapt every image in the album to its dimensions
await Promise.all(
album.map(async (image) => {
const adaptedImage = await adaptImageToAlbum(image);
// Add the photo to the final album
finalAlbum[image.index] = adaptedImage;
})
);
问题是,如果我改用这段代码
// Adapt every image in the album to its dimensions
await Promise.all(
album.map(async (image) => {
const adaptedImage = await adaptImageToAlbum(image);
// Add the photo to the final album
finalAlbum.push(adaptedImage);
})
);
finalAlbum未排序。还有其他方法可以不使用我共享的第一种方法吗?我的意思是,按顺序执行。还有一件事,关于性能,像我一样做会更好吗?
答案 0 :(得分:2)
您可以在处理项目之前对数组进行排序
const finalAlbum = await Promise.all(
album
.sort((a, b) => a.index - b.index)
.map((image) => adaptImageToAlbum(image));
);
从性能上看,这取决于您要处理的项目数。
通常,最好避免过早的优化,只要您没有性能问题,我建议您保持代码简洁明了。
答案 1 :(得分:2)
我将使用BlueBird Promise.each,通过它依次执行迭代,等待过程中的所有承诺:
const BlueBird = require("bluebird");
await BlueBird.each(album, async function(image) {
const adaptedImage = await await adaptImageToAlbum(image);
finalAlbum.push(adaptedImage);
})
为了直接说明这一点,以下代码以随机顺序填充数组:
const album = [1,2,3,4,5];
async function test(album) {
let finalAlbum = [];
await Promise.all(
album.map(async (image) => {
const adaptedImage = await new Promise((resolve) => {
setTimeout(() => {
resolve(image);
}, Math.random() * 100);
});
finalAlbum.push(adaptedImage);
})
)
console.log(finalAlbum); //random order
}
在Bluebird中,它将始终保持原始顺序:
const BlueBird = require("bluebird");
const album = [1,2,3,4,5];
async function test2(album) {
let finalAlbum = [];
await BlueBird.each(album, async function(image) {
const adaptedImage = await new Promise((resolve) => {
setTimeout(() => {
resolve(image);
}, Math.random() * 100);
});
finalAlbum.push(adaptedImage);
}
)
console.log(finalAlbum); // [1,2,3,4,5], keeps array order
}