简体   繁体   中英

How to write dependencies using 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 :

  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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM