我通过在执行Promise之间添加延迟来解决问题。我希望它们以特定的顺序执行。我试过Promise.mapSeries
但没有成功。
我的工作代码目前如下:
await Promise.delay(1000);
await accept(user.id, admin.id);
await Promise.delay(1000);
await accept(user.id, employee.id);
await Promise.delay(1000);
await reject(user.id, employee.id);
我已经Promise.mapSeries
尝试了此操作但没有成功:
const promises = [
accept(user.id, admin.id),
accept(user.id, employee.id),
reject(user.id, employee.id)
];
await Promise.mapSeries(promises, () => Promise.delay(1000));
答案 0 :(得分:5)
mapSeries
并没有帮助。构造数组和创建promises已经启动了操作,这些操作将并行运行,而不是按顺序运行。
最简单的解决方案是一个简单的循环:
const actions = [
{ action: accept, target: user, source: admin },
{ action: accept, target: user, source: employee },
{ action: reject, target: user, source: employee }
]
for (const a of actions) {
await Promise.delay(1000);
await a.action(a.target.id, a.source.id);
}
但您也可以使用mapSeries
代替:
await Promise.mapSeries(actions, a =>
Promise.delay(1000)
.then(() => a.action(a.target.id, a.source.id))
);
如果你的行为更具异质性,那就让它们发挥作用:
const actions = [
() => accept(user.id, admin.id),
() => accept(user.id, employee.id),
() => reject(user.id, employee.id)
];
for (const f of actions) {
await Promise.delay(1000);
await f()
}
await Promise.mapSeries(actions, async f => {
await Promise.delay(1000);
return f();
});
答案 1 :(得分:3)
如果要按顺序运行Promises,则需要延迟执行。你可以通过让你的数组返回一个函数来执行此操作,然后返回一个Promise并将其传递给mapSeries
:
const arr = [
() => Promise.resolve(1) /* () => accept(user.id, admin.id) */,
() => Promise.resolve(2) /* () => accept(user.id, employee.id) */,
() => Promise.resolve(3) /* () => reject(user.id, employee.id) */
];
// Now use mapSeries to execute the promises in sequence
Promise.mapSeries(arr, item => {
return Promise.delay(1000).then(item);
})
.then(arr => console.log(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.4.1/bluebird.js"></script>