A collection of ES7 async/await utilities. Install via NPM:
npm install asyncbox
Then, behold!
An async/await version of setTimeout
import { sleep } from 'asyncbox';
async function myFn () {
// do some stuff
await sleep(1000); // wait one second
// do some other stuff
};An async/await way of running a method until it doesn't throw an error
import { sleep, retry } from 'asyncbox';
async function flakeyFunction (val1, val2) {
if (val1 < 10) {
throw new Error("this is a flakey value");
}
await sleep(1000);
return val1 + val2;
}
async function myFn () {
let randVals = [Math.random() * 100, Math.random() * 100];
// run flakeyFunction up to 3 times until it succeeds.
// if it doesn't, we'll get the error thrown in this context
let randSum = await retry(3, flakeyFunction, ...randVals);
}You can also use retryInterval to add a sleep in between retries. This can be
useful if you want to throttle how fast we retry:
await retryInterval(3, 1500, expensiveFunction, ...args);Export async functions (Promises) and import this with your ES5 code to use it with Node.
var asyncbox = require('asyncbox')
, sleep = asyncbox.sleep
, nodeify = asyncbox.nodeify;
nodeify(sleep(1000), function (err, timer) {
console.log(err); // null
console.log(timer); // timer obj
});If you have a whole library you want to export nodeified versions of, it's pretty easy:
import { nodeifyAll } from 'asyncbox';
async function foo () { ... }
async function bar () { ... }
let cb = nodeifyAll({foo, bar});
export { foo, bar, cb };Then in my ES5 script I can do:
var myLib = require('mylib').cb;
myLib.foo(function (err) { ... });
myLib.bar(function (err) { ... });npm test