Skip to content

Instantly share code, notes, and snippets.

@getify getify/1.js
Last active Sep 13, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.