Ad

Node Async Await Code Writing Style Which One Is Good And Optimized

- 1 answer

I used to write code for async-await in (Style 1), other dev suggested me to write in (Style 2).

Can someone please explain to me what is the difference between both styles, for me it seems the same.

Code Style 1:

const fixtures = await fixtureModel.fetchAll();
const team = await teamModel.fetch(teamId);

Code Style 2:

const fixturesPromise = fixtureModel.fetchAll();
const teamPromise = teamModel.fetch(teamId);

const fixtures = await fixturesPromise;
const team = await teamPromise;
Ad

Answer

They are not the same.

The first will initialize a Promise, wait for it to complete, then initialize another Promise, and wait for the second Promise to complete.

The second will initialize both Promises at once and wait for both to complete. So, it will take less time. Here's a similar example:

// Takes twice as long as the other:

const makeProm = () => new Promise(resolve => setTimeout(resolve, 1000));

console.log('start');
(async () => {
  const foo = await makeProm();
  const bar = await makeProm();
  console.log('done');
})();

// Takes half as long as the other:

const makeProm = () => new Promise(resolve => setTimeout(resolve, 1000));

console.log('start');
(async () => {
  const fooProm = makeProm();
  const barProm = makeProm();
  const foo = await fooProm;
  const bar = await barProm;
  console.log('done');
})();

But you might consider making the code even clearer with Promise.all instead:

const [fixtures, team] = await Promise.all([
  fixtureModel.fetchAll(),
  teamModel.fetch(teamId)
]);
Ad
source: stackoverflow.com
Ad