1252748
1252748

Reputation: 15362

Using forEach to sequentially execute functions in Q

I'm attempting to run a series of functions based upon the Q API using their first strategy for sequences. This suggests the pattern:

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

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

What structure are each of the functions within the array meant to take? I am quite confused about when to use the return def.promise;. Is that simply always the last line? Will it frequently or always immediately follow def.resolve(someVar). Is something like this then ended structure?

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

So that each subsequent function within the array will receive the newly calculated value of f: in this case, if var initialVal = 1; and four functions each incrementing f++, the returned result will be 4? How do I access that returned value? console.log(result) prints { state: 'pending' } .

Upvotes: 3

Views: 819

Answers (1)

Roamer-1888
Roamer-1888

Reputation: 19298

What structure are each of the functions within the array meant to take?

Q.js allows promises to be created 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 libs are similar, but not necessarily so flexible. Native js Promises must be constructed with the third of these approaches.

However, in the real world you will only rarely need to create your own Promise. You will typically be dealing with promise-returning lib methods that someone else has written. For example :

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

How do I access that returned value?

The code is easier to understand if member name "result" is replaced with "promise", and result.then(f) is rewritten 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 now it should be clearer how the previous result is passed down the promise chain.

Accessing all previous promise results in the sequence is more complicated. The answers here discuss the subject comprehensively.

Upvotes: 2

Related Questions