I am having trouble with async in nodejs. In the following code
//Imagine we are inside a function
// many things here before reading a file
this.data_receiver; //want to this get file content
fs.readFile('/data.txt', (err, data) => {
if (err) throw err;
//console.log(data);
this.data_receiver= data; // get data
});
//I want to process data_receiver
......
The problem is that how can I get data little by little from a file and store it into some variables, then use that variable outside?
I am new to this async, having trouble.
The this
is not bounded to your function inside the callback. You should do:
this.data_receiver; //want to this get file content
var me = this;
fs.readFile('/data.txt', (err, data) => {
if (err) throw err;
//console.log(data);
me.data_receiver = data; // get data
});
console.log(this.data_receiver);
Also, this is about callback scope. While technically saying, it is "async functions", but it is more common to associate "async functions" to async
functions, such as:
async function foo() {
return Promise.resolve();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments