Sangharsh
Sangharsh

Reputation: 3019

How to write dependencies using async/await in Node.js

I have a scenario in Node.js application

Scenario

I want to ensure no promise is waiting un-necessarily.
That means p3, p4 are created as soon as p1 resolves
And similarly p5 is created as soon as p2 resolves

Have created a JSBin for this: https://jsbin.com/ruyozes/edit?js,console

Question:

  1. Can this code be made cleaner?
  2. OR Use more of async/await and less of Promise syntax?
  3. Is there any equivalent of async.auto (of callback world)

// noprotect

const startTime = Date.now();

const log = (...a) => {
  let timeDiff = Date.now() - startTime;
  console.log(timeDiff + ': ' + a.join(' '));
};

const createPromise = (tag, time) => {
  log(tag, 'created', time);
  return new Promise((resolve) => {
      setTimeout(resolve, time);
    })
    .then(() => {
      log(tag, 'fired', time);
    });
};

/*
 * Scenario
 * p1, p2 are independent promises
 * p3, p4 depend on p1 for data
 * p5 depends on p2 for data
 */
async function fn() {
  let p1 = createPromise('p1', 200);
  let p2 = createPromise('p2', 50);

  let p3, p4, p5;

  p1.then(() => {
    p3 = createPromise('p3', 1000);
    p4 = createPromise('p4', 500);
  });

  p2.then(() => {
    p5 = createPromise('p5', 300);
  });

  await Promise.all([p1, p2]);
  log('Waiting on p3, p4, p5 now');
  await Promise.all([p3, p4, p5]);

  log('All resolved');
}
fn();
<!DOCTYPE html>
<html>

<head>
  <meta name="description" content="Dependency tree with async/await">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser-polyfill.min.js'></script>
</head>

<body>

</body>

</html>

Upvotes: 3

Views: 1718

Answers (1)

Natan Camargos
Natan Camargos

Reputation: 549

Regarding to the first question, I suggest you do the following:

...
async function fn() {
  const p1 = createPromise('p1', 200);
  const p2 = createPromise('p2', 50);
  const p3 = p1.then(() => createPromise('p3', 1000));
  const p4 = p1.then(() => createPromise('p4', 500));
  const p5 = p2.then(() => createPromise('p5', 300));

  await Promise.all([p3, p4, p5]);

  log('All resolved');
}
...

Why? Being more strict, your code can lead to unwanted issues. Imagine that p3 = createPromise('p3', 1000); throws an error, what would be the result of such a situation?

p1.then(() => {
  p3 = createPromise('p3', 1000); // what if this line throws an error?
  p4 = createPromise('p4', 500); // this line will not be excecuted!
});

If it occurs, you'll not even create p4! In other words, p3, that shouldn't have a direct relationship to p4, ends up influencing p4. It can be avoided using my suggestion.

Upvotes: 3

Related Questions