我有以下代码:
Promise.map(myValues, async myValue => {
const owner = await findOwner(myValue);
return sendMessage(owner);
})
现在我想了解一下,如果我想每个值发送两个消息,我该怎么做?
Promise.map(myValues, async myValue => {
const owner = await findOwner(myValue);
/* I want both sendMessage and senMessageSpecific(owner) to happen but map expects just one return. How do I deal with this situation? */
sendMessage(owner);
sendMessageSpecific(owner);
})
如果在地图中我希望能够返回多个promise(在某些情况下),语法是什么?现在它显然不起作用,因为我做了退货,所以它永远也不会进入第二个承诺。
答案 0 :(得分:1)
我假设您的两个消息函数返回promise,并且您希望map等待两个。在这种情况下,您可以将它们包装在Promise.all
中。像这样:
Promise.map(myValues, async myValue => {
const owner = await findOwner(myValue);
return Promise.all([sendMessage(owner), sendMessageSpecific(owner)]);
})
或者,如果您不关心返回值,则可以像使用findOwner
一样等待两个函数。像这样:
Promise.map(myValues, async myValue => {
const owner = await findOwner(myValue);
await sendMessage(owner);
await sendMessageSpecific(owner);
})
两种功能都会同时发生。区别在于,在第一种情况下,它们将并行发生,而在最后一种情况下,它们将一个接一个地发生。