Ran*_*ane 0 javascript node.js
我读过地图的承诺,但如果地图位于函数内部,我似乎不知道如何实现它。
例如:
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))
}
Run Code Online (Sandbox Code Playgroud)
但是,我有这段代码,其中地图位于 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)
}
Run Code Online (Sandbox Code Playgroud)
您无法在.map, 期间控制异步代码。
致await 所有你能做到的承诺
await Promise.all(account.map(async () => {
// do your async thing
}));
Run Code Online (Sandbox Code Playgroud)
这读作“映射到承诺,然后等待所有承诺”。
| 归档时间: |
|
| 查看次数: |
2985 次 |
| 最近记录: |