user534785
user534785

Reputation: 2253

How to execute asynchronous functions in a loop using Q.js

I need to execute an asynchronous function inside a loop (with different parameters). Any ideas how it can be done using Q module in Node.js. Below is an example:-

function addAsync(a, b) {
    var deferred = q.defer();
    // Wait 2 seconds and then add a + b
    setTimeout(function() {
        deferred.resolve(a + b);
    }, 2000);
    return deferred.promise;
}

Q.all can be used(), but that runs all in parallel. I essentially need to execute them sequentially due to a project requirement.

Upvotes: 2

Views: 1094

Answers (2)

Kris Kowal
Kris Kowal

Reputation: 3846

You have a lot of options, but this should get you moving:

parameters.reduce(function (results, parameters) {
    return results.then(function () {
        return addAsync(parameters[0], parameters[1])
        .then(function (result) {
            results.push(result);
            return results;
        })
    });
}, Q([]))
.then(function (results) {
    // ...
})
.done()

I have a more enjoyable solutions coming in Q-IO https://github.com/kriskowal/q-io/pull/57

Reader(parameters)
.map(function (parameters) {
    return addAsync(parameters[0], parameters[1])
}, null, 1)
.all()
.then(function (results) {
    // ...
})

Where 1 is a parallelism limiter.

Upvotes: 1

Dmitry Matveev
Dmitry Matveev

Reputation: 5376

If you do not have to stick with Q.js I advise you to have a look at async.

Async is a popular asynchronous flow-control library that offers a wast amount of useful functions, including such functions as series or waterfall that does exactly what you need. Thanks :)

Upvotes: 4

Related Questions