Last active
April 19, 2020 00:17
-
-
Save liddiard/ae21d21a524069b43fa992d116750ccd to your computer and use it in GitHub Desktop.
Simple implementation of taking a callback-style function that accepts an `(err, result)` callback as its last argument and return that function promisified.
This file contains hidden or 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
// dummy callback func; randomly calls success or failure callback after 1 sec | |
const myFunc = (a, b, callback) => { | |
setTimeout(() => | |
Math.random() > 0.5 ? callback(null, 'success!') : callback('fail :('), | |
1000) | |
} | |
// test the dummy func | |
myFunc('foo', 'bar', (err, res) => { | |
if (err) { | |
console.log(err) | |
} else { | |
console.log(res) | |
} | |
}) | |
// take a function that accepts a "(err, result)"-style callback as its last | |
// argument and return a function that calls the passed function, but returns | |
// a promise that will resolve or reject | |
// use a `function` function so the `arguments` array is set to the proper | |
// value below | |
const promisify = (funcWithCallback) => function() { | |
return new Promise((resolve, reject) => | |
funcWithCallback(...arguments, (err, res) => | |
err ? reject(err) : resolve(res) | |
) | |
) | |
} | |
// "promisify" the callback-style function | |
const promisifiedFunc = promisify(myFunc) | |
// test it out! | |
try { | |
const res = await promisifiedFunc('foo', 'bar') | |
console.log(res) | |
} catch (err) { | |
console.log(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment