0

I want to explore util.promisify in nodejs. My below code fetch the data from files and also print for util.promisify which is now comment. I started to write my own function similar to promise which wait for the data either from db or file and then return the data. But I am getting empty string instead of data in my console.log.

I am new to node js. I want to use this in my important project which fetch data from db.

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

function read(file){
    var str="";
    setTimeout(()=>{
        fs.readFile(file,(err,data)=>{
            str=data;
        })
    },2000);
    return new Promise((resolve,reject)=>{
        resolve(str);
    });
}



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

let promiseArr=[read('/promise/data1.txt'),read('/promise/data1.txt'),read('/promise/data1.txt')];

async function main(){
    let [data1,data2,data3]=await Promise.all(promiseArr);
    console.log(data1.toString());
    console.log(data2.toString());
    console.log(data3.toString());
}

main();

imsaiful
  • 1,556
  • 4
  • 26
  • 49
  • No need for the timeout though: `function read(file) { return new Promise((resolve, reject) => fs.readFile(file, (err, data) => err ? reject(err) : resolve(data) ) ); } ` – HMR Oct 19 '19 at 21:48
  • Btw it would be a better practice to create the `promiseArr` inside the `main` function – Bergi Oct 19 '19 at 23:15

1 Answers1

1

A simple explanation of how util.promisfy works can be found here: https://medium.com/@suyashmohan/util-promisify-in-node-js-v8-d07ef4ea8c53

function read(file) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      fs.readFile(file, (err, data) => {
        if (err) reject(err);
        resolve(data);
      });
    }, 2000);
  })
}
Saghen
  • 26
  • 4