gpt4 book ai didi

javascript - 类 - 通过等待返回数据?

转载 作者:行者123 更新时间:2023-12-03 00:22:10 26 4
gpt4 key购买 nike

我正在学习如何将 class 与 Async/Await 结合使用。我认为我在 Run 类中的 getData 函数做错了。

使用 await get() 时应该输出“Hello World”(实验)。

当我运行脚本时,出现错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

类脚本:

class Run {
constructor() {
this.stop = false;
}

async getData(entry) {
if (this.stop) {
console.log("Stopped")
return;
}

return await this.get();
}

async get() {
return "Hello World";
}

stop() {
this.stop = true;
}
}

用法:

let run =  new Run();

run.getData(async (entry) => {
console.log(entry);
});

最佳答案

您收到错误是因为您忘记了 this 限定符:

async getData(entry) {
if (this.stop) {
^^^^
<小时/>

仅当您在 try/catch block 中使用 return wait 时才有意义。否则,它完全是多余的。

您应该在这里使用它。此外,getData 不使用其参数entry。您应该直接调用它:

console.log(await run.getData());
^^^^^

关于javascript - 类 - 通过等待返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com