Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save briancavalier/d75e3e3fc16ad4d43d50 to your computer and use it in GitHub Desktop.
Save briancavalier/d75e3e3fc16ad4d43d50 to your computer and use it in GitHub Desktop.
Promise.race answers differently with same inputs, depending on when it is called.
// Use native or try any of these promise impls.
// They all behave the same.
//var Promise = require('when').Promise;
//var Promise = require('rsvp').Promise;
//var Promise = require('bluebird');
// Here are 2 promises, p1 and p2. p2 always *actually* finishes
// first, since p1 finishes in 1 millisecond, and p2 is already
// finished when created
var p1 = new Promise(function(resolve) {
setTimeout(function() {
resolve('p1');
}, 1);
});
var p2 = Promise.resolve('p2');
// Given the same inputs, Promise.race answers differently
// depending only on when it is called.
// Logs p2
Promise.race([p1, p2]).then(console.log.bind(console));
// Logs p1
setTimeout(function() {
// Same inputs, different outcome
Promise.race([p1, p2]).then(console.log.bind(console));
}, 2);
@briancavalier
Copy link
Author

After some discussion with other implementors and folks intimately involved with ES6 Promises, it seems that Promise.race is intended to mean: "wait for at least one promise to settle, then produce the outcome of the settled promise with the lowest iteration index."

The place this gets weird is when you apply Promise.race to an array containing more than 1 already-settled promises. IOW, it can't be used reliably to discover the promise that settled earliest in time, because, once-settled, a promise does not retain any notion of the time at which it settled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment