【问题标题】:Resolve promises together in parallel并行解决 Promise
【发布时间】: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


【解决方案1】:

我部分理解了这个问题,但后来我觉得这是 nodejs 并发工作和我们试图实现并行性之间的区别,不是这样吗。

Nodejs 只是在任务之间切换,而不是实际上并行执行它。在这种情况下,子进程可能会对您有所帮助。

例如。如果你通过一个 sn-p

function done(i){
    try{
      return new Promise((resolve,reject)=>{
        console.log(i);
        resolve("resolved " + i + "th promise");
      })
    }catch(e){
      return null;
    }
}


let promises = [];
for(let i=0;i < 100000; i++){
  promises.push(done(i));
}

即使您不调用 Promise. ,控制台也会启动,好吗?这是你的问题,但事实上 Promise.all 不应该满足你的需求,应该通过产生子进程来在一定程度上实现并行性。

我试图让你提出的问题是做一些事情,比如首先生成一系列承诺并在调用 Promise.all 时启动所有这些,但我认为 Promise.all 也将同时运行而不是给你你想要达到的目标。

类似这样的东西 - https://htayyar.medium.com/multi-threading-in-javascript-with-paralleljs-10e1f7a1cf32 || How to create threads in nodejs

虽然大多数情况会在我们需要执行 cpu 密集型任务等时出现,但在这里我们可以实现称为 map reduce 的功能,将用户数组分成几部分并启动该数组以循环和发送通知。

我提出的所有解决方案都是为了实现某种并行性,但我不认为同时发送大量用户数组会很容易(使用更少的资源 - 实例配置等)

【讨论】:

  • 是的,你是对的。另外,已经编辑了问题的标题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 2018-02-06
  • 2018-05-22
  • 1970-01-01
  • 2017-11-16
  • 2023-03-31
相关资源
最近更新 更多