如何在异步函数内外共享变量?

时间:2017-02-25 08:12:21

标签: node.js asynchronous

我在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
......

问题是如何从文件中一点一点地获取数据并将其存储到某些变量中,然后在外部使用该变量?

我是这个异步的新手,遇到了麻烦。

1 个答案:

答案 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();
}