Last active
May 28, 2020 21:17
-
-
Save tomfa/f7e92ee780b0037133abd5bad12ad6e8 to your computer and use it in GitHub Desktop.
Swear
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
/* | |
* Swear | |
* | |
* Replaces callback functions with Promises | |
* | |
* Example – reading a file with fs: | |
* const fs = require('fs'); | |
* | |
* const path = '/path/to/file.txt' | |
* const fileContent = await swear(fs.readFile, path) | |
* | |
* Example – creating an async method of fs.readFile | |
* const readFile = makePromise(fs.readFile); | |
* | |
* const fileContent = await readFile(path); | |
*/ | |
async function swear(oldFunction, args) { | |
return new Promise((resolve, reject) => { | |
try { | |
oldFunction(args, (err, data) => (err ? reject(err) : resolve(data))); | |
} catch (exception) { | |
reject(exception); | |
} | |
}); | |
} | |
function makePromise(oldFunction) { | |
return (...args) => { | |
return new Promise((resolve, reject) => { | |
try { | |
oldFunction(...args, (err, data) => | |
err ? reject(err) : resolve(data) | |
); | |
} catch (exception) { | |
reject(exception); | |
} | |
}); | |
}; | |
} | |
module.exports = { swear, makePromise }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment