Last active
September 18, 2019 20:25
-
-
Save crates/59605936f6be35c9f912a2db09b62222 to your computer and use it in GitHub Desktop.
A demonstration of 3 methods running asynchronously with promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code was originally written to satisfy this question:
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.