Created
September 13, 2018 15:19
-
-
Save srikumarks/73102e85b953cc5460ca12bf917e8faa to your computer and use it in GitHub Desktop.
Supporting NodeJS style callbacks using async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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