electron封装使用net.request,同步返回结果

2023-12-29 11:31:54

electron封装使用net.request,同步返回结果

代码封装成一个函数,并使用同步方法返回结果。以下是修改后的代码:

const { app, BrowserWindow } = require('electron');
const { net } = require('electron');
 function sendRequestSync(url) {
??return new Promise((resolve, reject) => {
? ? const request = net.request(url);
? ? request.on('response', (response) => {
? ?? ?let data = '';
? ?? ? response.on('data', (chunk) => {
? ?? ???data += chunk;
? ?? ?});
? ?? ? response.on('end', () => {
? ?? ???resolve(data);
? ?? ?});
? ? });
? ???request.on('error', (error) => {
? ?? ?reject(error);
? ? });
? ???request.end();
??});
}
 function createWindow() {
??mainWindow = new BrowserWindow({
? ? width: 800,
? ? height: 600,
? ? webPreferences: {
? ?? ?nodeIntegration: true
? ? }
??});
? ?mainWindow.loadFile('index.html');
}
 app.whenReady().then(() => {
??createWindow();
? ?app.on('activate', function () {
? ? if (BrowserWindow.getAllWindows().length === 0) createWindow();
??});
});
 app.on('window-all-closed', function () {
??if (process.platform !== 'darwin') app.quit();
});
 // Example usage
async function main() {
??try {
? ? const responseData = await sendRequestSync('https://example.com');
? ? console.log(responseData);
? ? // TODO: Handle the response data
??} catch (error) {
? ? console.error(error);
? ? // TODO: Handle the error
??}
}
 main();

在上面的代码中,我将发送请求的代码封装成了一个名为 sendRequestSync 的异步函数。该函数返回一个Promise,当请求完成时会解析响应数据。如果请求发生错误,将会拒绝Promise并返回错误信息。
在 main 函数中,我们使用 await 关键字调用 sendRequestSync 函数,并使用 try/catch 块处理可能的异常。您可以在 try 块中处理返回的响应数据,并在 catch 块中处理错误。
请注意,由于Electron的主进程是基于Node.js的,因此我们可以使用 async/await 语法来处理异步操作,并使用 Promise 来返回结果。

文章来源:https://blog.csdn.net/airen3339/article/details/135284613
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。