Simple Async busy wait module for Node.JS
This module is installed via npm:
npm install --save busywait
Running:
const busywait = require('../lib/index').sync;
const waitUntil = Date.now() + 2500;
function syncCheck(iteration) {
console.log('running iteration', iteration);
return Date.now() > waitUntil;
}
busywait(syncCheck, {
sleepTime: 500,
maxChecks: 20
})
.then(function (result) {
console.log('finished after', result.iterations, 'iterations', 'with' +
' result', result.result);
});
or:
const busywait = require('../lib/index').async;
const waitUntil = Date.now() + 2500;
function asyncCheck(iteration) {
return new Promise(function (resolve, reject) {
console.log('running iteration', iteration);
if (Date.now() > waitUntil) {
return resolve(true);
} else {
return reject();
}
});
}
busywait(asyncCheck, {
sleepTime: 500,
maxChecks: 20
})
.then(function (result) {
console.log('finished after', result.iterations, 'iterations', 'with' +
' result', result.result);
});
Will result in:
running iteration 1
running iteration 2
running iteration 3
running iteration 4
running iteration 5
running iteration 6
finished after 6 iterations with result true
The syncCheckFn
first argument is the function to run on each iteration.
syncCheckFn
must be a function with a boolean return value.
The current iteration number will be passed as first argument to every call of syncCheckFn
.
sleepTime
- Time in ms to wait between checksmaxChecks
- The max number of checks to perform before failing
waitFirst
- Should we wait thesleepTime
before performing the first check (default: false)failMsg
- Custom error message to reject the promise with
Return value is a promise.
- The promise will be resolved if the
syncCheckFn
returned true within a legal number of checks. - The promise will be rejected if the
syncCheckFn
rejectedmaxChecks
times.
Promise resolved value:
iterations
- The number of iterations it took to finishresult
- Constanttrue
The asyncCheckFn
first argument is the function to run on each iteration.
syncCheckFn
must be a function with a promise return value.
The current iteration number will be passed as first argument to every call of asyncCheckFn
.
sleepTime
- Time in ms to wait between checksmaxChecks
- The max number of checks to perform before failing
waitFirst
- Should we wait thesleepTime
before performing the first check (default: false)failMsg
- Custom error message to reject the promise with
Return value is a promise.
- The promise will be resolved if the
asyncCheckFn
was resolved within a legal number of checks. - The promise will be rejected if the
asyncCheckFn
rejectedmaxChecks
times.
Promise resolved value:
iterations
- The number of iterations it took to finishresult
- The resolved value ofasyncCheckFn
Please make all pull requests to the master
branch and ensure tests pass
locally.