Tuesday, 11 April 2017

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

I have a scenario in Node.js application

Scenario

  • p1 to p5 are promises (In actual code they call database or web services)
  • p1, p2 can be created instantly (from data in request parameters)
  • p3, p4 depend on p1 for data
  • p5 depends on p2 for data

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: Can this code be made cleaner?
OR Use more of async/await and less of Promise syntax?

// 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>


via Sangharsh

No comments:

Post a Comment