如何在Javascript中用Q顺序运行promises? [英] How to sequentially run promises with Q in Javascript?

查看:125
本文介绍了如何在Javascript中用Q顺序运行promises?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难顺序运行promises。

I am having a hard time running promises sequentially.

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,on,a,time],但由于某种原因,它们会立即输出。

onceUponATime() should sequentially output ["Once", "upon", "a", "time"] but instead they are being output immediately for some reason.

jsFiddle here: http://jsfiddle.net/6Du42/ 2 /

jsFiddle here: http://jsfiddle.net/6Du42/2/

知道我做错了吗?

推荐答案


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

but instead they are being output immediately for some reason.

你正在调用它们这里:

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

你需要推 function(){return getDelayedString(str); } 。顺便说一下,你应该使用每个循环中使用推送到数组。 / Web / JavaScript / Reference / Global_Objects / Array / maprel =nofollow noreferrer> map 。实际上你并不是真的需要它,但可以直接减少超过字符串数组:

You would need to push function(){ return getDelayedString(str); }. Btw, instead of using pushing to an array in an each loop you rather should use map. And actually you don't really need that anyway but can reduce over the strings array directly:

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

    return strings.reduce(function (soFar, s) {
        return soFar.then(function() {
            return getDelayedString(s);
        });
    }, Q());    
}

哦,不要使用 document.write

这篇关于如何在Javascript中用Q顺序运行promises?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆