gpt4 book ai didi

javascript - 将 Async/Await 与 Array.map 结合使用

转载 作者:行者123 更新时间:2023-11-28 14:09:05 29 4
gpt4 key购买 nike

所以我知道 async/await 不适用于 map 。我只是返回我的请求并使用 Promise.all() 来执行它们。我的问题是,我里面还有其他 promise ,并且想知道 Promise.all() 是否也会以正确的顺序执行 map 内的那些 promise 。

这是代码:

const productImageIds = Object.keys(data.webImages)

for(let i = productImageIds.length; i--;){
const productId = productImageIds[i]
const images = data.webImages[productId]
const requests = images.map(async (image, i) => {
const name = `${productId}_${i}.${image.split(`.`).pop()}`
const imageStream = await downloadImage(image, name) // IS THIS WORKING CORRECTLY WITH USING PROMISE.ALL() ??
const res = sanityRequest({
...sanityConfig,
type: `images`,
endpoint: `assets`,
contentType: `image/jpeg`,
body: imageStream,
params: `?filename=${name}`,
})


await unlinkSync(name) // IS THIS WORKING CORRECTLY WITH USING PROMISE.ALL() ??
return res

})

const uploadedImages = await Promise.all(requests)
}

最佳答案

My question is that I have other promises inside and was wondering if the Promise.all() will also execute those inside the map in the correct order.

没有。

Promise.all() 将创建一个 promise ,当传递给它的所有 promise 都解决时,该 promise 就会解决。它对这些 Promise 的解析顺序没有影响(也不能,因为它们会在调用 Promise.all 之前开始运行)。

如果您想按顺序处理images的每个值(而不是并行),那么请使用常规的for循环。

关于javascript - 将 Async/Await 与 Array.map 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60227783/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com