Skip to content

Instantly share code, notes, and snippets.

@srikumarks
Created September 13, 2018 15:19
Show Gist options
  • Save srikumarks/73102e85b953cc5460ca12bf917e8faa to your computer and use it in GitHub Desktop.
Save srikumarks/73102e85b953cc5460ca12bf917e8faa to your computer and use it in GitHub Desktop.
Supporting NodeJS style callbacks using async/await
// Usage is like -
//
// let x = await task(obj, obj.method, arg1, arg2);
// do_something(x);
//
// where obj.method is a method that takes a NodeJS style callback
// as the last argument, which is left out when making the above call.
// The task function turns the callback backed function into a
// pseudo promise which the async/await mechanism can work with.
function task(target, fn, ...argv) {
let _succeed = null, _fail = null;
let callback = function cb(err, result) {
// Account for when the callback happens
// too quickly - perhaps synchronously -
// so that the _succeed and _fail variables
// have not yet been populated. Just force an
// async call in that case.
if (!_succeed) {
setTimeout(cb, 100, err, result);
return;
}
if (err) {
return _fail(err);
}
_succeed(result);
};
// Do the async task right away.
argv.push(callback);
fn.apply(target, argv);
return {
then: function (succeed, fail) {
// Store away the one shot continuations so that
// when the callback arrives, they can be called.
_succeed = succeed;
_fail = fail;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment