Skip to content

Instantly share code, notes, and snippets.

@shravan-shandilya
Last active April 21, 2020 08:15
Show Gist options
  • Save shravan-shandilya/ddf11c0fd039b44aa6c798033686a550 to your computer and use it in GitHub Desktop.
Save shravan-shandilya/ddf11c0fd039b44aa6c798033686a550 to your computer and use it in GitHub Desktop.
Converting Callback functions to Promises
// when 'func' is a function that expects callback as the first parameter
function promisify(func){
return (...args) => {
return new Promise((resolve,reject) => {
func.call(undefined, (err,res)=>{
if(err){
return reject(err);
}
return resolve(res);
},...args)
});
}
}
//when 'func' expects the last arguement as the callback function
function promisify(func){
return (...args) => {
return new Promise((resolve,reject) => {
func.call(undefined, ...args, (err,res)=>{
if(err){
return reject(err);
}
return resolve(res);
})
});
}
}
let setTimeoutPromise = promisify(setTimeout);
setTimeoutPromise(5000).then(()=> console.log("5 seconds elapsed"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment