【发布时间】:2021-05-17 11:18:09
【问题描述】:
我正在尝试一起解决一系列承诺。不知道该怎么做。让我分享一下它的伪代码。
async function sendNotification(user, notificationInfo) {
const options = {
method: 'POST',
url: 'http://xx.xx.xx:3000/notification/send',
headers:
{ 'Content-Type': 'application/json' },
body:
{ notificationInfo, user },
json: true,
};
console.log('sent');
return rp(options);
}
我已将sendNotification 方法包装在另一个方法中,该方法返回 rp(request-promise) 模块的承诺。
接下来我在 promise 数组中推送这个 sendNotification 方法,类似这样
const notificationWorker = [];
for (const key3 in notificationObject) {
if(notificationObject[key3].users.length > 0) {
notificationWorker.push(sendNotification(notificationObject[key3].users, notificationObject[key3].payload)); // problem is notification are going as soon as i am pushing in notificationWorker array.
}
}
// task 1 - send all notifications
const result = await Promise.all(notificationWorker); // resolving all notification promises together
// task 2 - update values in db , after sending all notifications
const result2 = await Promise.all(updateWorker); // update some values in db
在上面的代码中,我的问题是,一旦我将通知推送到notificationWorker 数组中,它就会立即发送。当我运行await Promise.all(notificationWorker)时,我希望所有通知一起出现@
不确定,如何实现我正在尝试的目标?
【问题讨论】:
-
您的代码对我来说看起来不错。您能否澄清一下“我的问题是,一旦我将通知推送到 notificationWorker 数组中,通知就会发送。我希望所有通知一起发送......”?
-
您希望的真正区别是什么?没有什么完全同时发生,但是所有代码都会立即运行,直到你的代码中真正的异步点被命中。为什么在这种情况下很重要,因为差异应该很小?
-
> 我正在尝试与 Promise.all(notificationWorker) 一起发送通知......这不是它的工作原理。
Promise.all返回一个 Promise,当所有输入 Promise 都解决时,该 Promise 就会解决。 -
您可能对
Promise.all()感到困惑。它不会发送您的任何消息。它所做的只是跟踪启动消息发送的函数返回的承诺。当您将承诺放入数组时,您开始发送消息。那是发送消息的时候。这与Promise.all()无关。它只是跟踪您从发起消息发送后得到的承诺。 -
rp(options)是做什么的?
标签: javascript async-await promise es6-promise