Skip to content

Instantly share code, notes, and snippets.

@crates
Last active September 18, 2019 20:25
Show Gist options
  • Save crates/59605936f6be35c9f912a2db09b62222 to your computer and use it in GitHub Desktop.
Save crates/59605936f6be35c9f912a2db09b62222 to your computer and use it in GitHub Desktop.
A demonstration of 3 methods running asynchronously with promises
function sleep(ms) {
return new Promise(resolve => {
console.log(`starting ${ms}`);
setTimeout(() => {
console.log(`done ${ms}`);
resolve(ms);
}, ms);
});
}
(async () => {
console.log('aPromise, bPromise, cPromise executed concurrently as promises are in an array');
const start = new Date();
const aPromise = sleep(2000);
const bPromise = sleep(500);
const cPromise = sleep(5);
const [a, b, c] = [await aPromise, await bPromise, await cPromise];
console.log(`sleeping done - got ${a} ${b} ${c} in ${new Date()-start}`);
})();
// Now, let's look at rejecting promises that go beyond a certain amount of time:
var errorSleep = function(para) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(' ErrorSleep')
}, 1000)
})
}
try {
var result1 = await sleep(1);
var result2 = await errorSleep(4);
var result3 = await sleep(1);
console.log('result1: ', result1)
console.log('result2: ', result2)
console.log('result3: ', result3)
} catch (err) {
console.log('err: ', err)
console.log('result1: ', result1)
console.log('result2: ', result2)
console.log('result3: ', result3)
}
//err: ErrorSleep
//result1: 1
//result2: undefined
//result3: undefined
/* How about some references?
https://stackoverflow.com/a/54526132/1098368
https://techbrij.com/javascript-promises-error-handling-chain
https://techbrij.com/javascript-async-await-parallel-sequence
http://exploringjs.com/es6/ch_promises.html
https://medium.com/@piotrkarpaa/async-await-and-parallel-code-in-node-js-6de6501eea48
https://hackernoon.com/asycn-await-bible-sequential-parallel-and-nest-4d1db7b8b95c
*/
@crates
Copy link
Author

crates commented Sep 18, 2019

This code was originally written to satisfy this question:

How do you get 3 promises to run asynchronously, while each one fetches something over REST, returning the added values from the results of all 3 REST calls as long as they finish in under 30 seconds, or the results of all those calls that finished within 30 seconds if the timer expires?

On further evaluation, it seems like this is a pretty straightforward use case for generator functions. I'll have to try my hand at another revision of this problem and see if I can come up with a generator-based solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment