javascript-使用q库在nodejs中进行循环
作者:互联网
以下是我拥有的功能
function start(){
var deferred = Q.defer();
for(var i=0; i < 3; i++){
second()
.then(third)
.then(fourth)
.catch(function(error){
console.log(error);
});
}
return deferred.promise;
}
function second(){
//does an http request
// returns promise
}
function third(){
//does an http request
// returns promise
}
function fourth(){
//takes the response of second and third function
//and compares the response
//returns promise
}
这是文件运行时的操作顺序:
second function
second function
third function
third function
fourth function
fourth function
(我知道为什么会这样,这是由于第二和第三功能中的I / O请求所致)
我想要的操作顺序
second function
third function
fourth function
second function
third function
fourth function
如何在nodejs中完成此操作?
这是上述问题的后续处理:
如何将值传递给.then(funcCall(value))中的函数,以便当
函数实际上被调用,它也获得一个可以使用的值.
解决方法:
您已经到了一半,只需要正确链接即可:
function start() {
var deferred = Promise.resolve();
for (var i = 0; i < 3; i++) {
deferred = deferred.then(second)
.then(third)
.then(fourth)
.catch(function(error) {
console.log(error);
});
}
return deferred.promise;
}
function second() {
return new Promise(function(r) {
console.log('second');
setTimeout(r, 100);
});
}
function third() {
return new Promise(function(r) {
console.log('third');
setTimeout(r, 100);
});
}
function fourth() {
return new Promise(function(r) {
console.log('fourth')
setTimeout(r, 100);
});
}
start();
用Q替换Promise.
标签:q,node-js,javascript 来源: https://codeday.me/bug/20191119/2036696.html