Skip to content

Instantly share code, notes, and snippets.

@olostan
Last active December 12, 2016 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olostan/47d5803e9838c4b0304dfdb179d07c71 to your computer and use it in GitHub Desktop.
Save olostan/47d5803e9838c4b0304dfdb179d07c71 to your computer and use it in GitHub Desktop.
Convert call-back style functions into async/await
function toAsyncFunction(f, thisObj) {
return function () {
let args = Array.prototype.slice.call(arguments);
return new Promise(function (resolve, reject) {
args.push(function (err, result) {
if (err) reject(err);
else resolve(result);
});
f.apply(thisObj, args);
});
}
}
function toAsync(obj) {
for (let p in obj) {
if (typeof (obj[p]) == 'function') obj[p] = toAsyncFunction(obj[p], obj);
}
return obj;
}
module.exports = { toAsync, toAsyncFunction };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment