我一直在试图找出答案。我如何将结果从promise循环推送到数组。谁能指出我在正确的位置?
const ids = [1, 2, 3]
let results = []
for (let id of ids) {
getLight(id)
.then(light => {
results.push(light)
})
.catch(err => {
console.log(err)
})
}
答案 0 :(得分:3)
承诺是异步的,所以您不能这样做。您可以使用Promise.all
来将承诺组合在一起,然后等待结果:
const ids = [1, 2, 3]
Promise.all(ids.map(id => getLight(id))).then(results => {
// do something with results here
})
打破这一点:
ids.map(id => getLight(id))
将id转换为未解决的承诺的数组。
Promise.all(promises).then(results => { ... })
解析所有的promise,并将结果(以正确的顺序)传递给回调
答案 1 :(得分:1)
const ids = [1, 2, 3]
let results = []
Promise.all(
ids.map((id) =>
getLight(id)
.then(light => {
results.push(light)
})
.catch(err => {
console.log(err)
})
)).then(() => console.log(results))
function getLight(id) {
return new Promise((res) => {
setTimeout(res, 1000)
}).then(() => `light for id: ${id}`)
}
使用异步/等待
(async() => {
const ids = [1, 2, 3]
let results = await Promise.all(
ids.map((id) =>
getLight(id))
)
console.log(results);
})()
function getLight(id) {
return new Promise((res) => {
setTimeout(res, 1000)
}).then(() => `light for id: ${id}`)
}