By Nick


2013-08-22 17:07:57 8 Comments

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 comments

@Bergi 2013-08-22 17:48:52

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.

@Nick 2013-08-23 08:15:44

Thanks for the answer and additional hints!

@FlavorScape 2015-03-26 20:54:01

yeah, it has to be a function factory to work, otherwise it executes immediately.

Related Questions

Sponsored Content

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6837413 View
  • 8413 Score
  • 96 Answer
  • Tags:   javascript arrays

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

95 Answered Questions

[SOLVED] How to validate an email address in JavaScript

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

3 Answered Questions

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

Sponsored Content