How to Write Your Own Promisify Function from Scratch
In this article, you will learn how to write your own promisify function from scratch.
Callback function
function promisify(func) {
return function(...args) {
return new Promise((resolve, reject) => {
func.call(this, ...args, (error, data) => {
if (error) {
reject(error)
} else {
resolve(data)
}
})
})
}
}
Test
const getSumPromise = promisify(getSum);
getSumPromise(22, 22)
.then(res => { console.log(res) }) // 44
.catch(e => { console.log(e) })