Advanced promise flow examples
let now = Date.now();
//// - advanced promise flow examples -
// - setup -
// resolves with the value 5
let completedSoon = Promise.resolve(5).then((res) => {
console.log(`${Date.now() - now}: completedSoon done`);
return res;
});
// completes after completedSoon
let pDelayed = new Promise((resolve, reject) => {
console.log(`${Date.now() - now}: timeout promise created`);
setTimeout(() => {
console.log(`${Date.now() - now}: timeout completed`);
resolve();
}, 2000);
});
// - examples -
// lets then() on completed soon AFTER it has been completed
let properPromise = pDelayed
.then(() => completedSoon)
.then((res) => console.log(`${Date.now() - now}: then(() => completedSoon): ${res}`)); // res is 5 as expected
// doing the following could be hard to debug and is incorrect
let improperPromise = pDelayed
.then(completedSoon) // instead of () => completedSoon
// DONT do this ^^^, IMO it should throw an error, maybe there is a good reason it doesnt though
// I tested it and it also doesnt actually wait on completedSoon
.then((res) => console.log(`${Date.now() - now}: then(completedSoon): ${res}`)) // res is undefined
// we can also then() on completedSoon multiple times! (and use pDelayed multiple times)
let properPromise2 = pDelayed
.then(() => completedSoon)
.then((res) => console.log(`${Date.now() - now}: #2 then(() => completedSoon): ${res}`)); // res is 5 as expected
//// - end of examples -
// runkit auto logs the last defined object so lets await so our logs are not dirtied with a print out of order
await properPromise2; // runkit lets you await outside of a user defined async, which is kind of dangerous i suppose,
// but can be useful for testing
let _ingnoreThis = "";
no comments