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+" ");
    }, 500);

    return deferred.promise;

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

    var promiseFuncs = [];

    strings.forEach(function(str) {

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

.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:

Any idea what I am doing wrong?


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

but instead they are being output immediately for some reason.

You are calling them already here:

//                                ^^^^^

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

89 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6155009 View
  • 7682 Score
  • 89 Answer
  • Tags:   javascript arrays

88 Answered Questions

[SOLVED] How to validate an email address in JavaScript

27 Answered Questions

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

41 Answered Questions

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

58 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

55 Answered Questions

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

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

Sponsored Content