我在nodejs中遇到异步问题。 在以下代码中
//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
......
问题是如何从文件中一点一点地获取数据并将其存储到某些变量中,然后在外部使用该变量?
我是这个异步的新手,遇到了麻烦。
答案 0 :(得分:1)
this
与回调内的函数无关。你应该这样做:
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);
此外,这是关于回调范围。虽然从技术上说,它是“异步函数”,但更常见的是将“异步函数”与async
函数相关联,例如:
async function foo() {
return Promise.resolve();
}