【问题标题】:How to wait for a process to terminate before it sends response如何在发送响应之前等待进程终止
【发布时间】:2019-02-19 09:23:26
【问题描述】:

我正在与 Electron 合作,我正在使用三页。 Index.html 我发送请求,Main.js 处理请求,Page.js 创建一些长异步函数。

我的问题是我不知道如何让主文件等待Page.js 进程完成,然后再将响应发送到 html 页面。

我尝试使用 promise 将数据发送回 html,但我收到错误消息,因为它说 .then() 函数不是函数。

索引.html

document.querySelector('#formhomepage').addEventListener('submit', function(e) {
        e.preventDefault();
        let date = document.getElementById("date-input").value;
        const {ipcRenderer} = require('electron')

        // send InputDate to main.js 
        ipcRenderer.send('asynchronous-message', date )

        // receive output from main.js
        ipcRenderer.on('asynchronous-reply', (event, arg) => {
          console.log(arg);
          document.getElementById('results').innerHTML = arg;

        });
        });

Main.js

ipcMain.on('asynchronous-message', (event, inputDate) => {

  var excel_n1 = require('./page.js');

  excel_n1(inputDate).then(result => event.sender.send('asynchronous-reply', result ) )
  .catch(error => {console.log("error")});

});

page.js

module.exports = async function(inputDate){
   // long await function with a lot of async and await
 }

【问题讨论】:

  • 你的承诺在哪里?问题是在您的excel_n1 函数中您没有得到响应?
  • 我得到了回复,但几分钟后。在 main.js 将响应发送到 Index.html 之前,我必须等待。我试图实现一个承诺,但没有成功。承诺在 page.js 文件的 async 函数中实现。
  • 在indexipcRenderer你想等待来自Mainexcel_n1函数的响应?等待page.js ?
  • 是的,完全正确。 excel_n1 变量是从文件 page.js 导入的函数
  • 您的.then(result) 是否返回结果?在excel_n1 函数中

标签: javascript node.js promise electron


【解决方案1】:

在您的page.js 中,您的承诺应如下所示

module.exports = function(inputDate){
  return new Promise(async(resolve, reject) => {
    try{
      ...your code
      resolve(response);
    } catch (e) {
      reject(e.message)
    }
  })
}

【讨论】:

  • Promise 函数参数不需要是async,尤其是如果你不打算在其中使用await。你已经返回了一个新的 Promise()
  • @MosèRaguzzini 你是对的,但是问题中指出他在page.js 中使用了很多awaits 这就是为什么我把async 放在那里
  • 对不起。我错过了
猜你喜欢
  • 2015-06-15
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
相关资源
最近更新 更多