Cancel Promise pattern (no cancellable promises)

Jan-Ivar Bruaroey jib at mozilla.com
Thu Oct 27 12:22:25 UTC 2016


Likely this would be more convincing without a bug. Here is the correct 
wait function:

let wait = (ms, cancel = new Promise(() => {})) => {
   let id, both = x => [x, x];
   cancel.then(...both(() => clearTimeout(id)));
   return Promise.race([new Promise(resolve => id = setTimeout(resolve, 
ms)), cancel]);
};

For caller flexibility, we want to cancel on any activity of the cancel 
promise, which would have been more apparent in an example that actually 
relied on clearTimeout working. Fiddle updated. PTAL!

.: Jan-Ivar :.



More information about the es-discuss mailing list