2016-09-25 48 views
-2

所以里面的变量,我有这样的代码:如何获取嵌套在另一个函数

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代码。

+0

1回答直接的问题,你不能2 。回答你的具体问题 - 那里的函数是异步的,因此你不能返回稍后填充的值。 – vlaz

+0

宣布全球。在你的'.on(“end”)'中将html的值赋给你的全局变量。摆脱'return html'。删除这个问题。阅读几十个其他问题完全一样 – Tibrogargan

回答

3

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

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

解析不启动,直到事件循环的下一个“滴答”。一般来说,假设大多数回调是异步发生的。你会想转换你功能也同步:

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); 
     }); 
    }); 
} 
+0

这实际上解决了我的问题!当它让我时会接受。 – willyb321