加入所有异步调用以返回一些结果 [英] join all async calls to return some result
本文介绍了加入所有异步调用以返回一些结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于这个问题,我想进行一些异步调用,最后等到所有调用完成,然后返回结果,该解决方案将是什么?
What will be the performant solution for this problem where I want to make some async calls, wait in last until all the calls are completed, then return the result.
function parseAndMatch(arg1, arg2){
async.all([
asyncCall1(arg1, arg2),
asyncCall2(arg1, arg2)]
).then( result => {
//do something with result;
return finalResult;
});
}
我尝试安装npm deasync
, asyncawait
, bluebird
和 async
软件包来解决此问题.但是我找不到解决方案.
I tried to fit npm deasync
, asyncawait
, bluebird
, and async
packages to solve this problem. But I couldn't find the solution.
推荐答案
在@wing答案的基础上,我使用本机 Promise
和npm deasync
库解决了此问题.但是我不确定它的效率和性能如何.
On the basis of @wing answer's I solved this problem using native Promise
and npm deasync
library. But I'm not sure how efficient and performant it is.
function parseAndMatch(callback) {
return Promise.all([
new Promise(function(resolve, reject) {
var sum = 1;
for (var i = 0; i < 10000; i++) {
sum++;
}
return resolve(sum);
}),
new Promise(function(resolve, reject) {
var sum = 1;
for (var i = 0; i < 90000; i++) {
sum++;
}
return resolve(sum);
}),
]);
}
function joinAndReturn(){
var done = false;
var result;
parseAndMatch().then((results) => {
result = results[0] + results[1];
done = true;
});
deasync.loopWhile(function(){return !done;});
return result;
}
console.log(joinAndReturn());//100002
这篇关于加入所有异步调用以返回一些结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文