Skip to content

Commit

Permalink
Add function for polling asynchronously
Browse files Browse the repository at this point in the history
Sourced from file-icons/atom@7a70b0ce, where the function was previously
named `condition`. Renamed and simplified to be clearer for general use.
  • Loading branch information
Alhadis committed Feb 24, 2018
1 parent 0a713dc commit fd54cca
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/functional.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,30 @@ function nerf(fn, context = null){
}


/**
* Keep calling a function until it returns a truthy value.
*
* @example poll(async () => (await fetch(url)).done);
* @param {Function} fn
* @param {Object} [opts={}]
* @param {Number} [opts.rate=100]
* @param {Number} [opts.timeout=0]
* @param {Boolean} [opts.negate=false]
* @return {Promise}
*/
async function poll(fn, opts = {}){
const {rate = 100, timeout = 0, negate = false} = opts;
const start = Date.now();
for(;;){
const result = await fn();
if(!negate === !!result) return result;
if(timeout && Date.now() - start > timeout)
throw new Error("Timed out");
await new Promise($ => setTimeout($, rate));
}
}


/**
* Monkey-patch an object's method with another function.
*
Expand Down

0 comments on commit fd54cca

Please sign in to comment.