如何在Electron中为electron-updater的autoUpdater.checkForUpdates()使用async/await机制
如何在Electron中为electron-updater的autoUpdater.checkForUpdates()使用async/await机制
嘿,这个问题我太懂了!autoUpdater.checkForUpdates()本身是基于事件驱动的,不是原生返回Promise的方法,所以直接加await根本不会生效。咱们只需要把它包装成一个Promise,就能在你的async函数里愉快地用await了,下面给你一步步改代码:
核心思路是用new Promise()把事件监听的逻辑包起来,通过update-available、update-not-available、error这几个事件来控制Promise的resolve和reject,这样就能用await等待检查更新的完整流程。
改造你的现有代码如下:
import { autoUpdater } from 'electron-updater'; private _checkForUpdates = async () => { let feedUrl = ''; try { feedUrl = await this._getFeedUrl(); this.autoUpdater.setFeedURL({ url: feedUrl }); // 把checkForUpdates包装成可await的Promise await new Promise((resolve, reject) => { // 定义各事件的处理函数 const handleUpdateAvailable = () => { console.log("检测到可用更新!"); // 这里可以加你自己的逻辑,比如弹窗通知用户 cleanupEventListeners(); resolve(); }; const handleUpdateNotAvailable = () => { console.log("当前已是最新版本,无需更新"); cleanupEventListeners(); resolve(); }; const handleError = (err: Error) => { console.error("检查更新时出错:", err); cleanupEventListeners(); reject(err); }; // 注册一次性事件监听(用once避免重复绑定) this.autoUpdater.once('update-available', handleUpdateAvailable); this.autoUpdater.once('update-not-available', handleUpdateNotAvailable); this.autoUpdater.once('error', handleError); // 执行更新检查 this.autoUpdater.checkForUpdates(); // 清理事件监听的辅助函数,防止内存泄漏 function cleanupEventListeners() { this.autoUpdater.off('update-available', handleUpdateAvailable); this.autoUpdater.off('update-not-available', handleUpdateNotAvailable); this.autoUpdater.off('error', handleError); } }); // 到这里,更新检查的流程已经完成,你可以继续写后续逻辑 console.log("更新检查流程结束"); } catch (e) { // 捕获检查过程中出现的所有错误 console.error("更新检查失败:", e); // 这里可以加用户提示,比如“检查更新失败,请稍后重试” } };
给你划几个关键注意点:
- 用
once注册事件监听:确保每个事件只触发一次,不会因为多次调用函数而重复绑定监听,避免逻辑混乱 - 一定要清理监听:执行完后用
off移除监听,避免内存泄漏,这一点很容易被忽略 - 统一错误处理:把
error事件绑定到reject,这样就能被外层的try/catch捕获到,不用分散处理错误
另外提一句,如果你用的是electron-updater的非常新版本,偶尔会有返回Promise的API,但大部分稳定版本还是需要自己包装的,上面的方法是最通用的解决方案,不管哪个版本都能用。
内容来源于stack exchange
相关产品推荐
相关产品推荐

