Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding asynchronous javascript

What is the difference between following piece of codes:

Code 1:

export default async function syncData() {
  await Promise.all([syncData1(), syncData2()]);
}

// called in sagas.js
function* x() {
  const res = yield call(syncData);
}

Code 2:

export default function syncData() {
  return Promise.all([syncData1(), syncData2()]);
}
// called in sagas.js
function* x() {
  const res = yield call(syncData);
}
like image 950
john doe Avatar asked Apr 25 '26 10:04

john doe


1 Answers

The difference between your two functions is await vs return. The missing await doesn't really matter, since returning a promise from an async function will always resolve with the promise result similar to return await. So the only difference is the implicitly returned undefined in the first solution.

Written out explicitly:

export default async function syncData() {
  const res = await Promise.all([syncData1(), syncData2()]);
  return undefined;
}

export default function syncData() {
  const res = await Promise.all([syncData1(), syncData2()]);
  return res;
}
like image 155
Bergi Avatar answered Apr 27 '26 22:04

Bergi