【问题标题】:How to sequentially run promises with Q in Javascript?如何在 Javascript 中使用 Q 顺序运行 Promise?
【发布时间】:2013-08-25 13:20:48
【问题描述】:

我很难按顺序运行 Promise。

var getDelayedString = function(string) {
    var deferred = Q.defer();

    setTimeout(function() {
        document.write(string+" ");
        deferred.resolve();
    }, 500);

    return deferred.promise;
};

var onceUponATime = function() {
    var strings = ["Once", "upon", "a", "time"];

    var promiseFuncs = [];

    strings.forEach(function(str) {
        promiseFuncs.push(getDelayedString(str));
    });

    //return promiseFuncs.reduce(Q.when, Q());
    return promiseFuncs.reduce(function (soFar, f) {
        return soFar.then(f);
    }, Q());    
};

getDelayedString("Hello")
.then(function() {
    return getDelayedString("world!")
})
.then(function() {
    return onceUponATime();
})
.then(function() {
    return getDelayedString("there was a guy and then he fell.")
})
.then(function() {
    return getDelayedString("The End!")
})

onceUponATime() 应该按顺序输出 ["Once", "upon", "a", "time"] 但由于某种原因它们会立即输出。

jsFiddle 在这里:http://jsfiddle.net/6Du42/2/

知道我做错了什么吗?

【问题讨论】:

    标签: javascript promise q


    【解决方案1】:

    但由于某种原因它们会立即输出。

    你已经在这里给他们打电话了:

    promiseFuncs.push(getDelayedString(str));
    //                                ^^^^^
    

    您需要推送function(){ return getDelayedString(str); }。顺便说一句,与其在each 循环中使用推送到数组,不如使用map。实际上,您实际上并不需要它,但可以直接在 strings 数组上使用 reduce

    function onceUponATime() {
        var strings = ["Once", "upon", "a", "time"];
    
        return strings.reduce(function (soFar, s) {
            return soFar.then(function() {
                return getDelayedString(s);
            });
        }, Q());    
    }
    

    哦,还有don't use document.write

    【讨论】:

    • 感谢您的回答和其他提示!
    • 是的,它必须是一个函数 factory 才能工作,否则它会立即执行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多