在_.map()中使用异步函数

时间:2016-12-27 06:38:39

标签: javascript node.js asynchronous lodash

我正在使用lodash库进行迭代。为此,我使用了_.map()函数。我有一个问题,我在_.map()中有一个异步函数。我的代码是这样的:

 let dataToRender = {};
 let modifiedData = _.map(myArray, (element) => {
      dataToRender.uuid = element.UID;
      dataToRender.pendingAmountReceived = element.$.SR;
      dataToRender.orderID = element.TransactionID;
      dataToRender.orderAmount = element.TransactionValue;
      dataToRender.orderDate = moment(element.TransactionTime, 'YYYY-MM-DDTHH:mm:ss');
      dataToRender.goal = element.Product.replace('amp;', '&');
      dataToRender.currentStatus = 'waiting';

      //Here CheckFilter is my asynchrounous function
      //I have to do calculation base on the response of this checkFilter

      checkFilter(requireParams)
        .then(data => {
          //If the response returned from checkFilter is false I have to include this data
          if (!data) {
            return requireParams;
          }
        });
    });
 res.json(modifiedData);

但是我在modifiedData中只得到了null。如何获取所有数据?

1 个答案:

答案 0 :(得分:2)

Bluebird提供了许多promise helper方法,包括Promise.map(),它只会在所有返回的promise都被解析时解析。

唯一的问题是,当undefined功能真实时,您的结果中最终会得到checkFilter值。 lodash的_.compact功能可以在这里提供帮助,如果您有更具体的过滤需求,可以使用_.filter

const Promise = require('bluebird');
let dataToRender = {};
Promise.map(myArray, element => {
  dataToRender.uuid = element.UID;
  dataToRender.pendingAmountReceived = element.$.SR;
  dataToRender.orderID = element.TransactionID;
  dataToRender.orderAmount = element.TransactionValue;
  dataToRender.orderDate = moment(element.TransactionTime, 'YYYY-MM-DDTHH:mm:ss');
  dataToRender.goal = element.Product.replace('amp;', '&');
  dataToRender.currentStatus = 'waiting';

  return checkFilter(requireParams)
    .then(data => {
      // If the response returned from checkFilter is false I have to include this data
      if (!data) return requireParams;
    });
})
.then(results => res.json(_.compact(results)) );