Ad
How To Write An Alternate Function Of Util.promisify In Node Js?
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();
Ad
Answer
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);
})
}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad