以下是我拥有的函数
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();
将Promise
替换为Q
。