【问题标题】:Async.reflect with Async.mapLimitAsync.reflect 与 Async.mapLimit
【发布时间】:2017-10-17 16:39:44
【问题描述】:

我想收集所有错误(如果有的话),从尝试将数据保存到集合中,但它永远不会通过回调完成。有人可以帮忙吗?

async.mapLimit(results, 5, async.reflect((result, callback) => {
  debugLog('Checking for repeating data');
  return HistoryModel.find({
      gameId: result.gameId,
      endDate: result.endDate
    })
    .then(response => {
      if (!response || response.length === 0) {
        debugLog('Saving data to history collection');
        return HistoryModel.create(result)
          .then(() => callback())
          .catch(err => callback(err, null));
      } else {
        debugLog('Data already exists');
        return callback(
          errorResponse('result',
            `The data with ${result.gameId} and ${result.endDate} already exists`), null);
      }
    })
}, (err, results) => {
  console.log(err);
  console.log(results);

  res.status(200).send(results);
}));

【问题讨论】:

    标签: javascript asynchronous async.js


    【解决方案1】:

    如果debugLog('Saving data to history collection');debugLog('Data already exists'); 都没有被调用,那么HistoryModel.find 可能已经失败了。

    我会将.catch移动到你的promise链的末尾,throwerrorResponse返回的错误,并在最后的catch中进行整个错误处理。

    async.mapLimit(results, 5, async.reflect((result, callback) => {
      debugLog('Checking for repeating data');
      return HistoryModel.find({
        gameId: result.gameId,
        endDate: result.endDate
      })
      .then(response => {
        if (!response || response.length === 0) {
          debugLog('Saving data to history collection');
          return HistoryModel.create(result)
                 .then(() => callback())
        } else {
          debugLog('Data already exists');
          throw errorResponse('result',
                              `The data with ${result.gameId} and ${result.endDate} already exists`)
        }
      })
      .catch(err => { // catch all error that happen in the Promise chain
        callback(err, null)
      })
    }, (err, results) => {
      console.log(err);
      console.log(results);
    
      res.status(200).send(results);
    }));
    

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 2017-10-09
      • 1970-01-01
      • 2015-08-04
      • 2018-01-16
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多