【发布时间】:2022-01-03 13:19:07
【问题描述】:
我已经阅读了地图的承诺,但如果地图在函数内部,我似乎不知道如何实现它。
例如:
async function1(){
await mongoose.connect(CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const account = await Account.find({
priority: { $lt: 50000 },
}).skip(i * 1000).limit(1000).sort("priority");
const promise1 = await account.map(async (item) => {
//make axios requests here
}
Promise.allSettled(promise1).then(()=> process.exit(0))
}
但是,我有这段代码,其中地图位于 for 循环内。
async function1(){
await mongoose.connect(CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
//axios requests
for (let i=0; i<50; i++){
const account = await Account.find({
priority: { $lt: 50000 },
})
.skip(i * 1000)
.limit(1000)
.sort("priority");
await account.map(async (item) => {
//make axios requests here
}
}
//should wait for the map inside the loop to finish before executing
process.exit(0)
}
【问题讨论】:
-
你不能等待
map()(map 不是异步的/不返回一个promise)但是你可以从map 中返回一个充满promise 的数组,然后await这个Promise。全部 -
你不能在 for 循环中
await。考虑使用await for而不是link -
部分。这个问题是针对地图中的承诺。我的问题是 for 循环中的地图中的承诺。
标签: javascript node.js