Javascript Q Promise Sequence Order with Arguments

Javascript Q Promise Sequence Order with Arguments

本文关键字:with Arguments Order Sequence Promise Javascript      更新时间:2023-09-26

>我正在使用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

问题就在这里:

sampleAsyncCall(400,"first")
    .then(sampleAsyncCall(300,"second"))
    .then(sampleAsyncCall(200,"third"))
    .then(sampleAsyncCall(100,"forth"));

.then()函数应接收函数作为参数,而不是承诺(函数调用解析为承诺)。

编辑:

尝试这样的事情:

sampleAsyncCall(400,"first")
    .then(function(){
        return sampleAsyncCall(300,"second")
    })
    .then(function(){
        return sampleAsyncCall(200,"third")
    })
    .then(function(){
        return sampleAsyncCall(100,"forth")
    });