【问题标题】:Async/Await not working for inserting data inside loop异步/等待不适用于在循环内插入数据
【发布时间】:2018-02-01 23:27:21
【问题描述】:

我有一些记录的对象数组,我想将这些记录插入一个循环中,但它不起作用。

req.notifications(对象数组):

[ { user_group: 'reporter',
    notification_type: 'email,dashboard',
    parent_id: 1 },
  { user_group: 'assignee',
    notification_type: 'email',
    parent_id: 1 },
  { user_group: 'superadmin',
    notification_type: 'sms,dashboard',
    parent_id: 1 } ]

模型功能:

exports.notificationAdd = async function(req, callback) {
    var notifications = req.notifications; 
    var _err = [];
    await Promise.all(notifications.map(async (notification) => {
        var schemaObj = new NotificationSchema(notification);
        await schemaObj.save(function(err, created){
            if(err){ _err.push(err); }
        });
    }));
    if(_err.length > 0) {
        callback({ code: 400, status: 'error', message: "Unable to add notification", data: _err});
    } else {
        callback({ code: 200, status: 'success', message: 'Notification successfully added!'});
    }
};

我收到以下错误:

\App\myProject\node_modules\mongodb\lib\utils.js:132
      throw err;
      ^

TypeError: Cannot read property '0' of null

我看到数据库,只插入了一条记录。当我调试代码时,我看到循环将转到下一个计数器,而不在循环内执行保存函数,仅在上次执行保存函数时。

谢谢。

【问题讨论】:

  • 我认为你混合和匹配太多了。如果你 await 一个承诺,它返回的不再是一个承诺,所以我认为你正试图在一个可能......不知道的数组上调用 Promise.all。向 schemaObj.save 添加回调可能会导致它不再返回 Promise,但这取决于您的持久性库。不过,您还 await 表示,所以即使它确实返回了一个 Promise,您也不会再次传递该承诺,而是首先解决它。
  • save 在你传递回调时是否会返回一个承诺?
  • 我使用 camintejs 作为 Cross DB ORM,所以我不知道是否有返回承诺。

标签: node.js promise async-await


【解决方案1】:

您需要使用for...of 来解决循环内的承诺。

类似这样的东西(未测试):

for(let notification of notifications){
  try {
    var schemaObj = new NotificationSchema(notification);
    await schemaObj.save();
  } catch (e) {
    _err.push(err)
  }
}

尽量不要将回调模式与承诺模式混用

【讨论】:

  • 那是为了顺序迭代。使用Promise.all+map 可以并发执行。
  • 不要使用for循环,而是使用async-parallel,其中还可以控制并发。
猜你喜欢
  • 2019-06-02
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 2020-08-02
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多