Created
January 20, 2016 06:41
-
-
Save cbrunnkvist/844909c7cd7d86b54957 to your computer and use it in GitHub Desktop.
A verbose example of making JS/ES6 async code feel synchronous using generator/yield
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
'use strict'; | |
const Promise = require('bluebird'); | |
function someAsyncTask() { | |
return new Promise(function(resolve) { | |
let delay = Math.floor(Math.random() * 10000); | |
setTimeout(function () { | |
resolve(delay); | |
}, delay); | |
}); | |
} | |
let main = Promise.coroutine(function* (sequenceName) { | |
console.log(sequenceName, 'starting 1st step'); | |
let result1 = yield someAsyncTask(); | |
console.log(sequenceName, 'starting 2nd step'); | |
let result2 = yield someAsyncTask(); | |
console.log(sequenceName, 'starting 3rd step'); | |
let result3 = yield someAsyncTask(); | |
console.log(sequenceName, 'done after', result1 + result2 + result3); | |
return result1 + result2 + result3; | |
}); | |
main('first sequence'); | |
main('second sequence'); | |
console.log('all systems go!'); |
@vphantom that's what I wanted to demonstrate: the two main
instances kick off in sequence (the two initial "starting" lines of output) but get their job done asynchronously, in parallell (the jumbled "step" output). ⏲️ ⏲️
Yeah, I could have completed it with Promise.all([main1, main2]).then(()=>{console.log('all done')})
but that would have ruined whatever simplicity 😸 remains in the example IMO.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, I didn't realize there was any response to this gist. :-)
@vkelman yes there is almost never any reason to pick
var
nowadays. Each function block is a block scope butconst
/let
takes away any ambiguities about the intent. Btw, I always strive after a "least privilege" code style, so I should have writtenconst
notlet
in all cases since I never change any references. I guess I sloppy-copy-pasted this example together.