gpt4 book ai didi

javascript - 如何使用异步并行合并最终回调中的所有回调结果

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:37 24 4
gpt4 key购买 nike

在这种情况下,我必须执行多个 CLI 命令,这些命令返回 JSON , 读取每个结果并获取特定字段,最后将它们合并为最终的 JSON .所有的 CLI 命令都是相互独立的。

var merge = require('./object-assign');

async.parallel(
[
function(callback) {
var response = {},
error {};
var test = exec(command);

test.stdout.on('data', function(data) {
response = data;
});

test.stderr.on('data', function(data) {
error.message = data;
});

test.on('close', function() {
//callback1
callback(error, response);
})
},

function(callback) {
var response = {},
error {};
var test = exec(command);
test.stdout.on('data', function(data) {
response = data;
});

test.stderr.on('data', function(data) {
error.message = data;
});

test.on('close', function() {
//callback2
callback(error, response);
})
}
//Few more callbacks

], function(err, results) {
//using object-assign to merge
var test = merge(result[0], result[1]);
//when callback1 completes result[0] is getting values where as result[1]
//is undefined since it is getting executed.
}
);

callback1 首先完成并向最终回调发送响应和结果,callback2 完成并发送其响应。如何确保所有回调都在最终回调中完成,以便我可以合并结果以获得最终的 JSON

这里异步并行是正确的方法吗?如果不是,什么对这种情况最好?

最佳答案

阅读 的引用资料 async.js parallel

Run the tasks array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main callback is immediately called with the value of the error. Once the tasks have completed, the results are passed to the final callback as an array.

Note: parallel is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.

例子:

async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
}
],
function(err, results){
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.

//manipulate the responses
//JSON.stringify(results);
});

关于javascript - 如何使用异步并行合并最终回调中的所有回调结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35728707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com