使用async.js系列识别回调数据
Identifying callback data with async.js series
我使用async.js调用3个异步函数,这些函数运行数据库查询,并在下面列出的最后一个函数的results[]
参数中返回数据:
async.series([
function(callback) {
datasetA.fetch(sqlQueryA).then(function(data) {
callback(null, data);
});
},
function(callback) {
datasetB.fetch(sqlQueryB).then(function(data) {
callback(null, data);
});
},
function(callback) {
datasetC.fetch(sqlQueryC).then(function(data) {
callback(null, data);
});
}
], function(error, results) {
// Results is array of data containing
// resultA, resultB, resultC.
});
我知道所有三个异步函数的结果都在results[]
参数中。但是,识别每个查询的结果的最佳方法是什么?我可以想出三种方法:
1。顺序-结果A将位于索引0,结果B位于索引1,结果C位于索引2。async.js文档中显然隐含了这一点,但没有明确说明。
2.在调用async.js callback(null, data)
之前修改回调参数:
async.series([
function(callback) {
datasetA.fetch(sqlQuery).then(function(data) {
data['query'] = 'A';
callback(null, data);
});
},
function(callback) {
datasetB.fetch(sqlQuery).then(function(data) {
data['query'] = 'B';
callback(null, data);
});
},
function(callback) {
datasetC.fetch(sqlQuery).then(function(data) {
data['query'] = 'C';
callback(null, data);
});
}
], function(error, results) {
for (var i=0; i < results.length; i++) {
// results[i].query will be A, B or C.
}
});
3. Inspect the data to determine which query ran.
I don't like 3 because it tightly couples the database schema with code (I only included it for completeness). But I'm less certain about whether 1 or 2 is better. Since the async.js documentation only implies order of results mirrors the order of the asynchronous functions in the array, I'm leaning towards option 2.
Above all else. Why am I even having this problem. Perhaps I'm using the async.js library incorrectly?
The question in the SO post Nodejs async series - pass arguments to next callback provided the answer.
By providing async.series()
with an object rather than an array, each asynchronous function becomes an object property and therefore has a key. The key can be used to identify the result.
Applied to my example, it looks like:
async.series({
A: function(callback){
datasetA.fetch(sqlQueryA).then(function(data) {
callback(null, data);
});
},
B: function(callback){
datasetB.fetch(sqlQueryB).then(function(data) {
callback(null, data);
});
},
C: function(callback){
datasetC.fetch(sqlQueryC).then(function(data) {
callback(null, data);
});
}
},
function(err, results) {
// results.A
// results.B
// results.C
});
- 将json回调数据转换为日期
- 如何降低此函数的复杂性,该函数根据数据类型进行回调
- 从AJAX回调函数中分离数据
- 行上的Primefaces数据表选择javascript回调
- 访问通过XHR.onreadystatechange回调中的XHR.send(data)发送的数据
- Angular 2中Observable中获取数据后的队列/回调函数
- Highcharts xAxis将格式化程序回调数据标记为空
- DimpleJS-在getTooltipText回调中获取原始数据
- Node.js,为事件分配回调函数'数据'
- 使用回调获取图像像素数据
- 试图从嵌套的回调函数返回数据
- 科尔多瓦 PhoneGap Android 回调与数据
- 如何显示查询回调数据结果仅从开始
- 使用async.js系列识别回调数据
- 如何使ajax成功回调数据全局可用
- jQuery:如何在Post回调数据中查找当前对象
- Pusher专用频道订阅成功回调数据
- 如何从 nodejs aws s3 getObject 回调数据中检索元数据
- 将Ajax回调数据转换为JQuery对象
- 将Ajax回调数据保存到一个不同步的变量中