如何获取嵌套在另一个函数中的变量

时间:2016-09-25 01:13:37

标签: javascript node.js

所以,我有这段代码:

function readLineMemory() {
loadFile = dialog.showOpenDialog({properties: ['openFile']});
console.log(loadFile);
var lr = new LineByLineReader(loadFile[0]);
lr.on('error', err => {
    return console.log(err);
});
lr.on('line', function (line) { // called every line
    // var html = '';
    const lineParse = JSON.parse(line);
    JSONParsed.push(lineParse);
    let htmlTabled = tableify(lineParse) + '<hr>';
    html = html + htmlTabled;
});
lr.on('end', function () { // called when file is read fully
    html = 'data:text/html,' + html;
})} return html

但是,当我尝试返回html值时,它只返回undefined。我一直在墙上撞了一会儿这个,我无法弄清楚我做错了什么。据我所知,代码不是异步。 html值实际上应该是我在另一个函数中使用的一串html代码。

1 个答案:

答案 0 :(得分:3)

根据我在代码中看到的内容,回调异步的:https://github.com/Osterjour/line-by-line/blob/master/line-by-line.js#L43-L45

setImmediate(function () {
    self._initStream();
});

在事件循环中的下一个“tick”之前,解析才会开始。通常,假设大多数回调是异步发生的,这是很好的。您需要将您的函数转换为异步:

function readLineMemory(cb) {
  let html = '';
  const loadFile = dialog.showOpenDialog({properties: ['openFile']});
  const lr = new LineByLineReader(loadFile[0]);
  lr.on('error', err => {
      cb(err);
    })
    .on('line', function (line) { // called every line
      const lineParse = JSON.parse(line);
      JSONParsed.push(lineParse);
      let htmlTabled = tableify(lineParse) + '<hr>';
      html = html + htmlTabled;
    })
    .on('end', function () { // called when file is read fully
      html = 'data:text/html,' + html;
      cb(null, html);
    });
}

(或IMO甚至更好地承诺):

function readLineMemory() {
  return new Promise(function (resolve, reject) {
    let html = '';
    const loadFile = dialog.showOpenDialog({properties: ['openFile']});
    const lr = new LineByLineReader(loadFile[0]);
    lr.on('error', err => {
        reject(err);
      })
      .on('line', function (line) { // called every line
        const lineParse = JSON.parse(line);
        JSONParsed.push(lineParse);
        let htmlTabled = tableify(lineParse) + '<hr>';
        html = html + htmlTabled;
      })
      .on('end', function () { // called when file is read fully
        html = 'data:text/html,' + html;
        resolve(html);
      });
  });
}
相关问题