0

I need to execute a function A and B in parallel, both functions have no dependency with each other.

I could use some Promise framework, however, I would like to learn how to do it with using Node.js async/await only.

My understanding it's both functions A and B start almost in parallel due to the async and await instructions.

So to ensure a delay on function A I inserted a 4 seconds synchronous delay in function A.

async function loop() {

    const process = require('child_process');              

    async function A() {
        process.execSync("sleep 4");        
        console.log("A");        
    }

    async function B() {
        console.log("B");
    }



    await A()
    await B()    


};

loop();

I expected to see on screen "B" and after 4 seconds, "A".

However, I seeing nothing for 4 seconds and after "A" and "B".

  • 4
    because that's what await does. it will wait on the promise, then when a result is returned from said promise, it will move to the next line and await the next promise. If you want them to run in parallel, await is the wrong tool. – Kevin B Jul 19 '19 at 18:02
  • Possible duplicate of [Call async/await functions in parallel](https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel) – Kevin B Jul 19 '19 at 18:03
  • I not sure if I understood, I think "await" it's to tell to NodeJS to "Do not wait" for function. – Amanda Osvaldo Jul 19 '19 at 18:04
  • 2
    async/await is syntactic sugar for .then. Putting two awaits one after the other puts the second promise inside a .then callback of the first. If you instead want promise.all functionality, you'll still need to use promise.all. – Kevin B Jul 19 '19 at 18:05
  • 1
    @AmandaOsvaldo it does the opposite. await tells NodeJS DO wait for function to finish. – Cal Irvine Jul 19 '19 at 18:24

0 Answers0