Created
September 25, 2016 18:01
-
-
Save craigdallimore/ff629bbf9d4d06eeebc2501204864fa5 to your computer and use it in GitHub Desktop.
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
// A function that takes a number and returns a Promise for nothing but | |
// some logging side effects. | |
const vow = num => new Promise(resolve => { | |
console.log(`start ${num}`); | |
setTimeout(() => { | |
console.log(`done ${num}`); | |
resolve(); | |
}, Math.random() * 500); | |
}); | |
// These promises will all start at about the same time | |
// and finish in an unpredictable way. | |
vow(1); | |
vow(2); | |
vow(3); | |
// These promises will each start when the previous one is done. | |
function* seq() { | |
yield vow(4); | |
yield vow(5); | |
yield vow(6); | |
} | |
// A cheap and hacky coroutine. | |
const run = generator => { | |
const iterate = result => result.done | |
? Promise.resolve(result.value) | |
: Promise.resolve(result.value) | |
.then(p => iterate(generator.next(p)), | |
e => iterate(generator.throw(e))); | |
try { | |
return iterate(generator.next()); | |
} catch (e) { | |
return Promise.reject(e); | |
} | |
}; | |
setTimeout(() => | |
run(seq()); | |
}, 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment