javascript - 如何在 promise.all 中异步等待
问题描述
我想制作一个 API 东西来加载口袋妖怪列表以及它的图像。得到列表,并想确保图片上的顺序对于这个 i console.log 相同的名称是正确的。并且顺序是错误的。在不同的地方尝试了一些异步等待,但无法弄清楚如何获得正确的顺序 https://codepen.io/DeanWinchester88/pen/ExvxdxX
Promise.all(arrForFetch)
.then(files => {
files.forEach(file => {
console.log("files", file)
process(file.json())
})
.catch(err => console.log("tobie pizda ucziekaj"))
})
let process = (prom) => {
console.log(prom)
prom.then(data => {
console.log(data.name)
})
}
解决方案
const results = await Promise.all(arrForFetch)
// do something with results array
您的问题是file.json()
异步的,因此需要从循环中作为另一个 Promise all 返回,或者在循环中等待。您可以映射承诺。
Promise.all(arrForFetch)
.then( files =>{
const more = files.map(file=>file.json().then(process))
return Promise.all(more)
})
.catch(err => console.log("tobie pizda ucziekaj"))
Promise.all(arrForFetch)
.then( async files =>{
for(const i=0; i<files.length; i++){
console.log("files", files[i])
process( await files[i].json() )
}
})
.catch(err => console.log("tobie pizda ucziekaj"))
推荐阅读
- python - 如何根据以下说明正确设置 R 工作区
- react-native - 无法在 iOS 上运行排毒测试
- design-patterns - 不同参数的 Kotlin 模式构建
- javascript - 这是缺失的,在反应输入 onChange
- python-3.x - Python - 从共享邮箱发送电子邮件而不使用“代表”
- python - 使用来自 python 的 ON DUPLICATE KEY UPDATE
- java - 如何为 container.listBlobs() 和 blob.exists() 生成单个 Account SAS
- asp.net-core - 如何修复 HMR Bundle Rebuild 不起作用
- ssl - 是否可以在 nginx 中使用 SSL Passthrough 重定向 TCP 连接
- python - 转换为非夏令时时区