Skip to content

Instantly share code, notes, and snippets.

@tomfa
Last active May 28, 2020 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/f7e92ee780b0037133abd5bad12ad6e8 to your computer and use it in GitHub Desktop.
Save tomfa/f7e92ee780b0037133abd5bad12ad6e8 to your computer and use it in GitHub Desktop.
Swear
/*
* 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