How to sequentially run promises with Q in Javascript?

≡放荡痞女 提交于 2019-11-26 01:09:10

问题


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() should sequentially output [\"Once\", \"upon\", \"a\", \"time\"] but instead they are being output immediately for some reason.

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

Any idea what I am doing wrong?


回答1:


but instead they are being output immediately for some reason.

You are calling them already here:

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

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());    
}

Oh, and don't use document.write.



来源:https://stackoverflow.com/questions/18386753/how-to-sequentially-run-promises-with-q-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!