Last active
April 21, 2020 08:15
-
-
Save shravan-shandilya/ddf11c0fd039b44aa6c798033686a550 to your computer and use it in GitHub Desktop.
Converting Callback functions to Promises
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
// 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