4

I have 2 codes

1 code

async function foo() {
    const result1 = asyncFunc1();
    const result2 = asyncFunc2();
    return [result1, result2];
}

2 code

async function foo() {
    const [result1, result2] = await Promise.all([
        asyncFunc1(),
        asyncFunc2(),
    ]);
return [result1,result2];
}

question Is there any difference between the two?

montrealist
  • 5,593
  • 12
  • 46
  • 68
  • 3
    If there were `await`s in the first example it would be series, rather than parallel. – jonrsharpe Aug 14 '19 at 17:19
  • 5
    you didn't use `await` in the first example, so you are not waiting for the completion of the async functions, thus `result1` and `result2` will be equal to promises instead of result values – Olivier Boissé Aug 14 '19 at 17:23
  • 8
    @OlivierBoissé means 1 code synchronously 2 code asynchronously ? –  Aug 14 '19 at 18:00

3 Answers3

2

As the comments state, you did not await the function calls in the first snippet, so you will get promises as return values. However if you used await, one major difference is that in the first snippet, asyncFunc2 isn't executed until asyncFunc1 is resolved (assuming you use await). Whereas, in the second snippet, asyncFunc2 is executed right after asyncFunc1 regardless of whether it has resolved.

Promise.all will return the results in the order in which you pass the functions.

See docs for Promise.All and Await

JBaczuk
  • 13,886
  • 10
  • 58
  • 86
0

As per the comments, there is essentially no difference in the two, other than the fact that you have not awaited the results from the two async functions, so you're gonna end up with just the promise objects. Async functions don't await scoped promises / async code automatically, they just allow you to use the await keyword, which is just stopping the execution until the underlying promise is resolved.

Here's an attempt to illustrate those differences.

What's important to note is that the returned values for the first function are not 1, 2 as would be expected.

const asyncFunc = (a) => {
    return new Promise((resolve) => {   
      setTimeout(() => resolve(a), 1000);
  })
}

const asyncFunc1 = () => asyncFunc(1);
const asyncFunc2 = () => asyncFunc(2);

async function foo() {
    const result1 = asyncFunc1();
    const result2 = asyncFunc2();
    return JSON.stringify({ result1, result2 });
}

async function foo2() {
    return [result1, result2] = await Promise.all([
        asyncFunc1(),
        asyncFunc2(),
    ]);
}


(async () =>{
    const el = document.createElement('div');
    el.appendChild(document.createTextNode(await foo()));
    el.appendChild(document.createTextNode(await foo2()));
    document.querySelector('body').appendChild(el);
})();


// {"result1":{},"result2":{}} 1,2

Here's a fiddle to play around with; jsfiddle.

4m1r
  • 12,234
  • 9
  • 46
  • 58
-1

Just find it out! Here is a snippet that shows all major differences:

const timer = ms => new Promise(res => setTimeout(res, ms));

async function one() {
  console.log("1 one called");
  await timer(2000);
  console.log("1 one done");
}

async function two() {
  console.log("2 two called");
  await timer(1000);
  console.log("2 two done");
  // throw new Error; // Uncomment to see another interesting behaviour
}

(async function main() {
  const startParallel = Date.now();
  await Promise.all([one(), two()]);
  console.log(`parallel done, took ${Date.now() - startParallel}`);

  const startSerial = Date.now();
  await one();
  await two();
  console.log(`serial done, took ${Date.now() - startSerial}`);
})();
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151