我正在使用here
所述的Q序列(Nodejs)我需要按顺序返回这些异步调用,即使它们需要不同的时间。我怎么能这样做?
我试过了:
function sampleAsyncCall(wait,order) {
var deferred = Q.defer();
setTimeout(function() {
console.log(order)
deferred.resolve();
}, wait);
return deferred.promise;
}
sampleAsyncCall(400,"first")
.then(sampleAsyncCall(300,"second"))
.then(sampleAsyncCall(200,"third"))
.then(sampleAsyncCall(100,"forth"));
Returns:
forth
third
second
first
令人困惑的是,如果我将其重写为不使用参数,则按我想要的顺序返回。
function first() {
var deferred = Q.defer();
setTimeout(function() {
console.log("first")
deferred.resolve();
}, 400);
return deferred.promise;
}
function second() {
var deferred = Q.defer();
setTimeout(function() {
console.log("second")
deferred.resolve();
}, 300);
return deferred.promise;
}
function third() {
var deferred = Q.defer();
setTimeout(function() {
console.log("third")
deferred.resolve();
}, 200);
return deferred.promise;
}
function forth() {
var deferred = Q.defer();
setTimeout(function() {
console.log("forth")
deferred.resolve();
}, 100);
return deferred.promise;
}
first().then(second).then(third).then(forth);
Returns:
first
second
third
forth
答案 0 :(得分:2)
问题在于:
sampleAsyncCall(400,"first")
.then(sampleAsyncCall(300,"second"))
.then(sampleAsyncCall(200,"third"))
.then(sampleAsyncCall(100,"forth"));
.then()
函数应作为参数接收函数和不 promise (函数调用解析为)。
编辑:
尝试这样的事情:
sampleAsyncCall(400,"first")
.then(function(){
return sampleAsyncCall(300,"second")
})
.then(function(){
return sampleAsyncCall(200,"third")
})
.then(function(){
return sampleAsyncCall(100,"forth")
});