如何根据异步调用的返回值做出决策? [英] How to make decisions based on return value of async calls?
本文介绍了如何根据异步调用的返回值做出决策?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Node.js
while(list != []) {
apiCall.then(function(data){
list = data;
});
}
其中apiCall是按如下方式构造的承诺:
return new Promise(function (fulfill, reject){
request("url", function (error, response, body){
try {
fulfill(body);
} catch (error) {
reject(error);
}
}, reject);
});
因为api调用是异步的,所以出现了问题并且循环永远不会结束.我该如何解决这个问题?
Because the api calls are asynchronous, something goes wrong and the loop never ends. How can I fix this issue ?
推荐答案
You can run functions with callbacks inside the loops synchronously using SynJS. Here is a working code to illustrate:
var SynJS = require('synjs');
var request = require('request');
function myFunction1(modules) {
var list, i=0;
while(i<5) {
modules.request("http://www.google.com", function (error, response, body){
list = body;
console.log("got it!", i, new Date());
modules.SynJS.resume(_synjsContext); //<-- indicates that callback is finished
});
SynJS.wait(); //<-- wait for callback to finish
i++;
};
};
var modules = {
SynJS: SynJS,
request: request,
};
SynJS.run(myFunction1,null,modules,function (ret) {
console.log('done');
});
这是结果:
got it! 0 Thu Jan 05 2017 18:17:20 GMT-0700 (Mountain Standard Time)
got it! 1 Thu Jan 05 2017 18:17:20 GMT-0700 (Mountain Standard Time)
got it! 2 Thu Jan 05 2017 18:17:21 GMT-0700 (Mountain Standard Time)
got it! 3 Thu Jan 05 2017 18:17:21 GMT-0700 (Mountain Standard Time)
got it! 4 Thu Jan 05 2017 18:17:21 GMT-0700 (Mountain Standard Time)
done
这篇关于如何根据异步调用的返回值做出决策?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文