O
O
Oleg2015-12-15 20:41:03
JavaScript
Oleg, 2015-12-15 20:41:03

How to make a loop with asyncawait, the iterations of which would be executed in parallel?

var exp = [0,1];
Test();

function Test() {
    return async(function() {
        await([exp.forEach(con)]);  //  (1)
        console.log('finish');
    })();
}

function con(num) {
    return async(function() {
        console.log('start');
        return await(opcha);
    })();
}

function opcha() {
    return new Promise(function(resolve,reject) {
        user.find(function(err,doc) {
            console.log(doc);
            resolve(doc);
        });
    });
}

It produces the following:
start
start
finish
[]
[]
And I need it to be like this:
start
start
[]
[]
finish
I can fix this by doing the following in line (1): await(con), but then it will stop at each individual iteration , but still I would like to implement parallelism.
Thank you for your attention.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-12-15
@halalala

await Promise.all(exp.map(con));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question