使用Async/Await的类中getData函数报错:未处理Promise拒绝
让我们一步步拆解你遇到的问题,然后修复你的代码:
问题1:stop方法与实例属性命名冲突
你在类里同时定义了实例属性this.stop = false和方法stop(),当你调用run.stop()时,会把原本的方法覆盖成布尔值true——这会导致后续再想调用stop()时直接报错(因为它已经不是函数了),同时判断逻辑也会变得混乱。
问题2:getData的调用方式完全错误
你调用run.getData(async (entry) => { console.log(entry); }),但getData的参数entry并没有被用作回调函数——getData是异步函数,它返回的是一个Promise,而不是接受回调来处理结果。
问题3:未处理Promise的潜在拒绝
虽然当前你的get()方法不会抛出错误,但异步函数返回的Promise如果被拒绝(比如后续get()里出现网络请求失败、抛出异常等情况),必须被捕获处理,否则就会触发UnhandledPromiseRejectionWarning。
修复后的完整代码
class Run { constructor() { // 改名避免和stop方法冲突 this.isStopped = false; } async getData() { if (this.isStopped) { console.log("Stopped"); return; } // 捕获get()可能抛出的错误 try { return await this.get(); } catch (err) { console.error("获取数据失败:", err); // 可以选择重新抛出或返回默认值 throw err; } } async get() { return "Hello World"; } stop() { this.isStopped = true; } } // 正确用法1:在异步函数中使用await + try/catch (async () => { const run = new Run(); try { const result = await run.getData(); console.log(result); // 输出"Hello World" } catch (err) { console.error("处理错误:", err); } })(); // 正确用法2:使用Promise的.then() + .catch() const run2 = new Run(); run2.getData() .then(result => console.log(result)) .catch(err => console.error("处理错误:", err)); // 测试stop功能 const run3 = new Run(); run3.stop(); run3.getData().then(result => console.log(result)); // 输出"Stopped",result为undefined
关键修正说明
- 将实例属性
this.stop改为this.isStopped,彻底避免和stop()方法的命名冲突; - 调整
getData的调用逻辑:异步函数返回Promise,需要用await(在异步函数内)或.then()接收结果,而非传递回调; - 在
getData内部和调用处都添加了错误捕获逻辑,确保所有Promise的拒绝都被处理,不会出现警告; - 使用立即执行的异步函数来包裹
await调用(因为await只能在异步函数中使用)。
内容的提问来源于stack exchange,提问作者I'll-Be-Back
相关产品推荐
相关产品推荐

