【问题标题】:node wait for iteration to complete before callback节点在回调之前等待迭代完成
【发布时间】:2018-08-27 17:46:17
【问题描述】:

我在 node.js 中有一个 lambda 函数来发送推送通知。

在该函数中,我需要遍历我的用户,在回调之前为每个用户发送通知。

理想情况下,我希望迭代并行执行。

最好的方法是什么?

我的代码目前如下,但它没有按预期工作,因为最后一个用户并不总是最后一个被处理的用户:

var apnProvider = new apn.Provider(options);

var iterationComplete = false;

for (var j = 0; j < users.length; j++) {
    if (j === (users.length - 1)) {
        iterationComplete = true;
    }

    var deviceToken = users[j].user_device_token;
    var deviceBadge = users[j].user_badge_count;

    var notification = new apn.Notification();

    notification.alert = message;

    notification.contentAvailable = 1;

    notification.topic = "com.example.Example";

    apnProvider.send(notification, [deviceToken]).then((response) => {

        if (iterationComplete) {
            context.succeed(event);
        }
    });
}

【问题讨论】:

    标签: node.js parallel-processing aws-lambda iteration async.js


    【解决方案1】:

    改用Promise.all - 将每个user 的关联apnProvider.send 调用映射到数组中的Promise,当数组中的所有Promises 都被解析时,调用回调:

    const apnProvider = new apn.Provider(options);
    const userPromises = users.map((user) => {
      const deviceToken = user.user_device_token;
      const deviceBadge = user.user_badge_count;
      const notification = new apn.Notification();
      notification.alert = message;
      notification.contentAvailable = 1;
      notification.topic = "com.example.Example";
      return apnProvider.send(notification, [deviceToken]);
    })
    Promise.all(userPromises)
      .then(() => {
        context.succeed(event);
      })
      .catch(() => {
        // handle errors
      });
    

    【讨论】:

    • 谢谢。我以前没有使用过承诺。似乎运作良好。
    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2019-06-11
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多