Using forEach to execute functions sequentially in Q

I am trying to run a series of API based functions Q

using my first strategy for sequences . This says about the pattern:

var funcs = [foo, bar, baz, qux];

var result = Q(initialVal);
funcs.forEach(function (f) {
    result = result.then(f);
});
return result;

      

What structure do each of the functions in the array do? I am very confused when to use return def.promise;

. Is it just always the last line? Will it often or always follow immediately def.resolve(someVar)

. Something like this structure that ended?

function foo(f){
    var def =  Q.defer();
    f++;
    def.resolve(f);
    return def.promise;
}

      

So that each subsequent function inside the array gets the newly computed value f

: in this case, if there are var initialVal = 1;

four functions, each of which increments f++

, the returned result will be 4

? How do I access this returned value? console.log(result)

displays { state: 'pending' }

.

+3


source to share


1 answer


What structure do each of the functions in the array do?

Q.js allows you to create promises in several ways. For example:

function foo(value) {
    var def =  Q.defer();
    def.resolve(value + 1);
    return def.promise;
}

function foo(value) {
    return Q(value + 1);
}

function foo(value) {
    return Q.Promise(function(resolve, reject) {
        resolve(value + 1);
    });
}

      

Other Promise libraries are similar, but not necessarily as flexible. Native js promises should be built with the third of these approaches.

However, in the real world, you will rarely need to create your own promises. You are usually dealing with the promised lib methods that someone else wrote. For example:

function foo(value) {
    return lib.doSomethingAsync(value, and, other, params);
}

      



How do I access this returned value?

The code is easier to understand if the principal name "result" is replaced with a "promise" and result.then(f)

overwritten with an anonymous function that calls f()

.

function performAsyncSequence() {
    var promise = Q(initialVal);
    funcs.forEach(function (f) {
        promise = promise.then(function(previousResult) {
            return f(previousResult);
        });
    });
    return promise;
}

      

This is 100% equivalent to the code in the question, but it should now be clearer how the previous result is passed along the promise chain.

Accessing all previous promise results in a sequence is more complex. The answers here discuss the subject in detail.

+2


source







All Articles