Skip to content

Instantly share code, notes, and snippets.

@getify
Last active September 13, 2019 04:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/5b5f58f4cd754b1f9b7d4835b8ec542e to your computer and use it in GitHub Desktop.
Save getify/5b5f58f4cd754b1f9b7d4835b8ec542e to your computer and use it in GitHub Desktop.
microtask queue got me singin' the blues
// VERSION 1 -- broken
async function *main() {
yield ready;
}
var resolve1;
var resolve2;
var ready = new Promise(function c(res){
resolve1 = res;
});
var other = new Promise(function c(res){
resolve2 = res;
});
resolve1("hare"); // winner should be "hare"
resolve2({ value: "tortoise" }); // but winner is "tortoise" :/
Promise.race([
main().next(),
other,
])
.then(function t({ value }){
console.log(`The winner is: ${value}`); // The winner is: tortoise
});
// VERSION 2 -- broken
async function *main() {
yield ready;
}
var resolve1;
var resolve2;
var ready = new Promise(function c(res){
resolve1 = res;
});
var other = new Promise(function c(res){
resolve2 = function r(v){ Promise.resolve(v).then(res); }; // ONLY THIS LINE WAS CHANGED!
});
resolve1("hare"); // winner should be "hare"
resolve2({ value: "tortoise" }); // but winner is "tortoise" :/
Promise.race([
main().next(),
other,
])
.then(function t({ value: winner }){
console.log(`The winner is: ${winner}`); // The winner is: tortoise
});
// VERSION 3 -- "fixed", but UGH :(
async function *main() {
yield ready;
}
var resolve1;
var resolve2;
var ready = new Promise(function c(res){
resolve1 = res;
});
var other = new Promise(function c(res){
resolve2 = function(v){ Promise.resolve().then(()=>v).then(res); }; // ONLY THIS LINE WAS CHANGED!
});
resolve1("hare"); // winner should be "hare"
resolve2({ value: "tortoise" }); // and it is! :(
Promise.race([
main().next(),
other,
])
.then(function t({ value: winner }){
console.log(`The winner is: ${winner}`); // The winner is: hare
});
// VERSION 4 -- also "fixed", but double UGH :(
async function *main() {
yield ready;
}
async function *main2() {
yield other;
}
var resolve1;
var resolve2;
var ready = new Promise(function c(res){
resolve1 = res;
});
var other = new Promise(function c(res){
resolve2 = res;
});
resolve1("hare"); // winner should be "hare"
resolve2("tortoise"); // and it is! :(
Promise.race([
main().next(),
main2().next(),
])
.then(function t({ value: winner }){
console.log(`The winner is: ${winner}`); // The winner is: hare
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment