How to convert Array.forEach to asynchronous with Q.js?

I need to execute a dynamic function for all elements of an array, but Array.forEachexecute in sequence, and I need to execute in asynchronous mode.

items.forEach(function(item) {
    doSomething(item);
});

I try this:

var promises = [];

items.forEach(function(item) {
    var promise = function() {
        return Q.fcall(function() {
            doSomething(item);
        });
    };
    promises.push(promise());
});

Q.all(promises).then(function () {
    otherFunction(datacontext.mainList); //use datacontext.mainList filled.
});

But execution is always in sequence, and I need execution in parallel.

Method doSomething(item):

function doSomething(item) {
        var children = getChildren(item); //get data from local with manager.executeQueryLocally
        var total = getTotal(children); //simple calculations
        datacontext.mainList.push({
            name: item.firstName() + ' ' + item.lastName(),
            total: total
        });
    }

Please help me.

+3
source share
2 answers

This answer assumes that doSomethingit is an asynchronous operation itself. This means that he will have to give way to the cycle of events and wait for at least one event at a time. If it doSomethingis synchronous, there is no benefit to building it asynchronously.

. (n + 1) (n). , . .

Array Q.all, , doSomething jobs :

return Q.all(jobs.map(doSomething))

.

return jobs.reduce(function (previous, job) {
    return previous.then(function () {
        return doSomething(job);
    });
}, Q());

, , reduceRight .

return jobs.reduceRight(function (next, job) {
    return function (previous) {
        return doSomething(job).then(function (result) {
            if (result.isGood(previous)) return result;
            return next(result);
        });
    });
}, function fallthrough(previous) {
    throw new Error("No result was satisfactory");
})();

, , , , reduce .

return functions.reduce(Q.when, Q());

Qs readme , , https://github.com/kriskowal/q#tutorial

+21

, , , . ...

promises.push(promise());

...

promises.push(promise);
0

All Articles