我正在使用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。如何获取所有数据?
答案 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)) );