Last active
October 11, 2022 08:04
-
-
Save aderchox/d4f6e2b1b5ed2d80ddd36ea9528f237e to your computer and use it in GitHub Desktop.
Promisification Quick Example
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
// This example illustrates how a synchronous method from the "fs" module could be promisified. | |
// Note that Node provides a built-in promisified fs module itself out of the box, and this snippet is just for illustration purposes. | |
const fs = require("fs"); | |
// Non-promisified (async using callbacks, which can lead to callback hell... 👿🔥) | |
fs.readFile("./package.json", function callback(err, data) { | |
const package = JSON.parse(data.toString("utf8")); | |
console.log(package.name); | |
}); | |
// Here's where we promisify the fs.readFile() method used above: | |
async function fsReadFilePromisified(param) { | |
return new Promise((resolve, reject) => { | |
fs.readFile(param, (err, data) => { | |
if (err) { | |
reject(data); | |
} else { | |
resolve(data); | |
} | |
}); | |
}); | |
} | |
// Using the promisified API using .then() syntax (async using .then(), old, not recommended) | |
fsReadFilePromisified("./package.json") | |
.then((response) => { | |
const package = JSON.parse(response.toString("utf8")); | |
console.log(package.name); | |
}) | |
.catch((err) => console.log(err)); | |
// Using the promisified API using async/await syntax (async using async/await, modern, recommended) | |
// This is an IIFE in form of `(()=>{})()`. | |
// If you'd rather not use an IIFE and want to use top-level async/await, just turn | |
// this module into an ESM module (e.g., by changing the file extension from .js to .mjs). | |
(async () => { | |
try { | |
const resp = await fsReadFilePromisified("./package.json"); | |
const package = JSON.parse(resp.toString("utf8")); | |
console.log(package.name); | |
} catch (error) { | |
console.error(error); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment