developerasun / myCodeBox-web

Open source code box for web developers.
Apache License 2.0
5 stars 0 forks source link

[RESEARCH] Javascript/promise: Promisify #272

Open developerasun opened 2 years ago

developerasun commented 2 years ago

topic : understanding how to use promisify in Node.js

read this

The util.promisify() method basically takes a function as an input that follows the common Node.js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.

Promisify is used when you want to convert a callback function into a promise based function. Nowadays, is used promises because let the developers to write more structured code.

const fs = require("fs");
const util = require("util");

// readFile method is based on callback
fs.readFile("./app.js", (err, data) => {
  if (err) console.error(err);
  else console.log(data.toString());
});

console.log("=====================");

const readFile = util.promisify(fs.readFile);

// now readFile is based on promise
readFile("./app.js", { encoding: "utf-8" })
  .then((val) => console.log(val))
  .catch((err) => console.log(err))
  .finally(() => console.log("all done"));

console.log("=====================");

// or use await/async

async function useWithAsyncAwait() {
  const result = await readFile("./app.js", { encoding: "utf-8" });
  console.log(result);
}

useWithAsyncAwait();

reference