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

标签 javascript node.js async-await

我正在学习如何将 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/

相关文章:

javascript - jQuery 报告 Firefox iframe 中的元素高度不正确

node.js - 如何等待 Redis 连接?

c# - .NET HttpClient 在使用 await 关键字时挂起?

c# - Async TaskCompletionSource 调用方法两次

javascript - 根据文件中的需要列出文件中的依赖项

javascript - 场景在哪里异步/等待 promise ?

javascript - 为什么透明对象在动画 Canvas 元素时变得不透明?

Javascript 查找两个二维数组之间的共同值

javascript - 将字符串传递到 Onchange

javascript - mysql/node.js 如何使/假同步?