Only the last one executed in an asynchronous process (Promise) executing in parallel is resolved


For example, suppose you write code that pulls a resource on the server with ajax and reflects the result in a view. Roughly speaking, it looks like this.


/api/items/1, /api/items/2 is not guaranteed which one will come back first. If it comes back later first, I think that the result will probably be different from what I expected.

Therefore, if you count the number of executions and compare it with the number of counts recorded when it becomes resolved, when it matches, it is executed at the end, so it flows back as it is, If it is different, reject it It creates a layer.

var latest = (() => {
  var ids = {};

  return key => {
    ids[key] = ids[key] || 0;
    var id = ++ids[key];
    return x => id === ids[key] ? x : Promise.reject(new Error('old promise!'));

Now only the last asynchronous process executed in parallel will be resolved, dude.

var sleep = t => new Promise(resolve => setTimeout(() => resolve(t), t));
var log = console.log.bind(console);
var error = console.error.bind(console);

sleep(100).then(latest('a')).then(log, error);
sleep(200).then(latest('a')).then(log, error);
sleep(300).then(latest('a')).then(log, error);
sleep(150).then(latest('a')).then(log, error); // resolved
sleep(340).then(latest('b')).then(log, error);
sleep(120).then(latest('b')).then(log, error);
sleep(110).then(latest('b')).then(log, error);
sleep(200).then(latest('b')).then(log, error); // resolved
Author by


Updated on December 25, 2015