gpt4 book ai didi

javascript - promise : How to resolve an unknown amount of promises

转载 作者:行者123 更新时间:2023-11-30 07:01:39 25 4
gpt4 key购买 nike

我有一个函数,它接收数组中未知数量的建筑物 ID,即 [4,5],然后调用一个返回它的名称和描述的函数。鉴于这是一个未知数,我不知道如何处理。我尝试创建一个 for 循环,但毫无结果,我完全迷路了。你在下面看到的是我将整个数组发送给一个函数,但我想遍历每个元素并单独调用该函数

编辑:谢谢大家的热心回复。你一直非常乐于助人和支持

function getBuilding(buildingId){
return new Promise(function(resolve,reject){
Building.getBuilding(buildingId).then((buildingInfo)=>{
resolve(buildingInfo);
});
})
}

最佳答案

您想使用 Promise.all , all 的 promise 将在数组中的所有项都已解析后解析。然后,这将返回一个包含结果数组的 promise ,其中第一项是第一个建筑 ID 结果,第二个是第二个 ID,依此类推。

function getBuilding(ids) {
let promises = []
// We will assume `getInfo()` returns a promise that resolves the buildings info
ids.forEach(id => promises.push(getInfo(id)))
return Promise.all(promises)
}

function getInfo(id) {
// Resolves the info after a random amount of time to simulate
// something that may take some time to execute.
return new Promise(resolve => setTimeout(() => resolve({id}), Math.floor(Math.random() * 5000)))
}

console.log('Just a moment, calculating data...')
getBuilding([3, 5, 7, 9]).then(results => {
console.log('building id', results[0].id) // buildingId = 3
console.log('building id', results[1].id) // buildingId = 5
console.log('building id', results[2].id) // buildingId = 7
console.log('building id', results[3].id) // buildingId = 9
})

关于javascript - promise : How to resolve an unknown amount of promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55938388/

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