Node.js - 使用异步库 - async.parallel 传递数组
Node.js - Using the async lib - async.parallel pass an Array
我有以下函数可以并行获取数据。获取数据完成后,结果将通过回调函数中的 'results' 变量提供。我需要参数化而不是硬编码 'products'、'images' 等。我需要能够传递一个数组。 (即我需要说 var fetchInParallel = function (id, res, names)
)其中 names = ['products', 'images']
我该怎么做?我尝试了 using forEach 但没有成功。
var fetchInParallel = function (id, res) {
async.parallel(
[
function (callback) {
commonService.findById('products', id, function (result) {
callback(false, result);
})
},
function (callback) {
commonService.findById('images', id, function (result) {
callback(false, result);
})
}
],
function (err, results) {
// handle errors code
var products = results[0];
var volatile = results[1];
var target = stitch(products,images);
res.send(target)
}
);
}
您正在寻找 map
function:
function fetchInParallel(id, names, res) {
async.map(names, function(name, callback) {
commonService.findById(name, id, function (result) {
callback(null, result);
});
}, function (err, results) {
if (err)
… // handle error code
var target = stitch(results); // combine names with results
res.send(target)
});
}
您可以使用 async.map 而不是像这样并行;
var fetchInParallel = function (id, res,names) {
async.map(names,
function (name,callback) {
commonService.findById(name, id, function (result) {
callback(null, result);
})
},
function (err, results) {
}
);
}
我有以下函数可以并行获取数据。获取数据完成后,结果将通过回调函数中的 'results' 变量提供。我需要参数化而不是硬编码 'products'、'images' 等。我需要能够传递一个数组。 (即我需要说 var fetchInParallel = function (id, res, names)
)其中 names = ['products', 'images']
我该怎么做?我尝试了 using forEach 但没有成功。
var fetchInParallel = function (id, res) {
async.parallel(
[
function (callback) {
commonService.findById('products', id, function (result) {
callback(false, result);
})
},
function (callback) {
commonService.findById('images', id, function (result) {
callback(false, result);
})
}
],
function (err, results) {
// handle errors code
var products = results[0];
var volatile = results[1];
var target = stitch(products,images);
res.send(target)
}
);
}
您正在寻找 map
function:
function fetchInParallel(id, names, res) {
async.map(names, function(name, callback) {
commonService.findById(name, id, function (result) {
callback(null, result);
});
}, function (err, results) {
if (err)
… // handle error code
var target = stitch(results); // combine names with results
res.send(target)
});
}
您可以使用 async.map 而不是像这样并行;
var fetchInParallel = function (id, res,names) {
async.map(names,
function (name,callback) {
commonService.findById(name, id, function (result) {
callback(null, result);
})
},
function (err, results) {
}
);
}