Async.reflect与Async.mapLimit

时间:2017-10-17 08:29:50

标签: javascript asynchronous async.js

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

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);
}));

1 个答案:

答案 0 :(得分:0)

如果同时调用debugLog('Saving data to history collection');debugLog('Data already exists');,则HistoryModel.find可能已失败。

我会将.catch移到您的保证链的末尾,并throw errorResponse返回错误,并在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);
}));