异步操作完成后,从ipcMain向ipcRenderer发送响应

时间:2019-06-13 22:59:24

标签: javascript node.js asynchronous electron fast-csv

我正在通过编写应分析和分析.csv文件的应用程序来学习Electron。作为它的前端部分,我正在使用Vue.js。接下来是初始功能:用户选择一个文件,主进程对其进行解析,该文件的摘要作为Vue组件的一部分显示在客户端。下面的代码:

//background.js
import Analyzer from './Analyzer'
analyzer = new Analyzer();

ipcMain.on('data:upload', (event, data) => {
    let options = {
      filters: [{ 
        extensions: ['csv']
      }] 
    };
    let filepath = dialog.showOpenDialog(options);
    analyzer.loadDataCSV(filepath);  //executes async code
    event.sender.send('data:upload', analyzer.getState());// doesn't wait
})                                                        // async code to be completed 
                                                          // so the 'state' I'm sending 
                                                          // is actually incorrect


//Analyzer.js - class that i've wrote
import csv from 'fast-csv'
...
loadDataCSV(filepath) {
    if (!filepath) return;
    this.dataWSFilepath = filepath;
    this.showDataCard = true;
    let rowsCount = 0;
    csv. //async part
        fromPath(filepath, { delimiter: "|" })
        .on("data", function (data) {
            if (data[9] == 'NCR') rowsCount++;
        })
        .on("end", function () {
            this.NCRCount = rowsCount //Variable I'm expecting to be 
                                      //changed inside the Vue component
        });
}
getState(){ return { NCRCount: this.NCRCount }}
...

请告诉我正确的方法,等待将loadDataCSV()的异步部分完成,然后再将答案发送给ipcRenderer。

0 个答案:

没有答案