electron中在main.js中调用custom.js中导出的异步方法
electron中在main.js中调用custom.js中导出的异步方法下面是一个示例,展示如何在`main.js`中调用`custom.js`中导出的异步方法。我们将`custom.js`中的异步方法导出,并在`main.js`中直接调用它。
### 1. 在`custom.js`中定义和导出异步方法
// js/custom.js
async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched from custom.js!");
}, 2000);
});
}
// 导出异步方法
module.exports = { fetchData };
### 2. 在`main.js`中调用`custom.js`中的异步方法
const { app, BrowserWindow } = require('electron');
const path = require('path');
const customModule = require('./js/custom.js'); // 导入自定义 JS 文件
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js') // 使用 preload.js 进行安全通信
}
});
win.loadFile('index.html');
// 调用 custom.js 中的异步方法
callFetchData(); // 调用异步方法
}
// 定义一个异步函数来调用 fetchData
async function callFetchData() {
const data = await customModule.fetchData(); // 等待异步方法的结果
console.log(data); // 输出: Data fetched from custom.js!
}
app.whenReady().then(createWindow);
### 3. 启动应用
确保你的项目结构正确,然后运行 Electron 应用。你应该能在控制台看到以下输出:
Data fetched from custom.js!
### 总结
- 在`custom.js`中定义一个异步方法`fetchData`并导出。
- 在`main.js`中导入`custom.js` ,并定义一个异步函数`callFetchData`来调用`fetchData` 。
- 使用`await`等待异步方法的结果,并在控制台输出结果。
通过这种方式,你可以在`main.js`中轻松调用`custom.js`中的异步方法。
页:
[1]