我一直在试图弄清楚。如何将结果从 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)
})
}
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}`)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)