Reputation: 3019
I have a scenario in Node.js application
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 datap5
depends on p2
for dataI 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:
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
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