gpt4 book ai didi

node.js - 在 foreach 语句中解决 promise

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:27 24 4
gpt4 key购买 nike

我正在尝试解决多个 promise 并在所有 promise 都解决后返回一些东西

我环顾四周但找不到解决方案,或者我只是不理解。

我的代码:

export const setLeagues = (res: any, leaguesArray: any) => {
leaguesArray.forEach((element: any) => {
firebaseAdmin.firestore().collection('leagues').add(element)
.catch((err: any) => { res.send(err) })
})

当 forEach 中的所有 promise 都已解决时,我想执行 res.send('Successfully Added!)

最佳答案

如果您使用 Promise.allmap,这就足够简单了:

export const setLeagues = (res: any, leaguesArray: any) => {
// Wrap in a Promise.all, and use .map instead of .forEach:
Promise.all(leaguesArray.map((element: any) => {
// Make sure to return promise here...
return firebaseAdmin.firestore().collection('leagues').add(element)
.catch((err: any) => { res.send(err) })
})).then(() => {
// Do things here that need to wait for all promises to resolve.
})
}

我会注意到,由于 Promise.all 的工作方式,您可能还想更改处理错误的方式。 Promise.all 在任何包装的 promise 拒绝时立即拒绝,或者在所有包装的 promise 都解决时解决。因此,我建议移动您的 .catch 以链接 Promise.all 而不是内部 promise 以避免发送两次响应:

export const setLeagues = (res: any, leaguesArray: any) => {
// Wrap in a Promise.all, and use .map instead of .forEach:
Promise.all(leaguesArray.map((element: any) => {
// Make sure to return promise here...
return firebaseAdmin.firestore().collection('leagues').add(element)
})).then(() => {
// Do things here that need to wait for all promises to resolve.
res.send('Successfully Added!')
}).catch((err: any) => {
// Consider moving error handler to here instead...
res.send(err)
})
}

关于node.js - 在 foreach 语句中解决 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432930/

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