我有一个必须运行async.map的数组。就每个数组对象的并行运行而言,该功能很好,记录为“Result for ...”。但是,迭代函数的返回回调似乎是用最后一个对象的结果覆盖第一个数组对象,该对象被记录为“最终结果......”。
async.map(array, getInfo, function (asyncError, asyncStatus)
{
if(asyncError)
{
return callback(asyncError);
}
else
{
console.log(' Final Result <<<<<<<<<<<------- '+JSON.stringify(asyncStatus));
//return callback(null, asyncStatus);
}
});
function getInfo(passedArray, callback)
{
Analyser(passedArray.productName, passedArray.productPurchaseRecord, function(opError, opStatus)
{
if(opError)
{
return callback(opError);
}
else
{
console.log(' Result for '+passedArray.productName+' ------->>>>>> '+JSON.stringify(opStatus));
return callback(null, opStatus);
}
});
}
输出: -
Result for bmwX1 ------->>>>>> [{"month":"January","totalSales":8,"newOrders":3}]
Result for AudiA4 ------->>>>>> [{"month":"January","totalSales":11,"newOrders":4}]
Final Result <<<<<<<<<<<------- [[{"month":"January","totalSales":8,"newOrders":3}],[{"month":"January","totalSales":8,"newOrders":3}]]
答案 0 :(得分:0)
您的代码看起来有点像这样:
try {
const result = await scramjet.fromArray(array)
.reduce(async (last, item) => getInfo(item))
} catch (e) {
console.error("error", e)
}
您需要稍微更改getingo功能,以便像这样异步:
async function getInfo(passedArray, callback) {
return new Promise(resolve, reject) {
Analyser(passedArray.productName, passedArray.productPurchaseRecord,
function(opError, opStatus) {
if(opError) {
return reject(opError);
} else {
console.log(' Result for '+passedArray.productName+' ------->>>>>> '+JSON.stringify(opStatus));
return resolve(opStatus);
}
});
}
这提供了一个漂亮,干净的代码,代码逐个运行(如果你想并行运行代码,你可以使用map)。 reduce方法与Array.prototype.reduce