【问题标题】:Class - return data via await?类 - 通过等待返回数据?
【发布时间】:2019-06-13 13:39:16
【问题描述】:

我正在学习如何将 class 与 Async/Await 一起使用。我想我在 Run 类中的 getData 函数做错了。

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

当我运行脚本时,我得到一个错误:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在异步函数内部抛出 没有 catch 块,或拒绝未处理的承诺 使用 .catch()。 (拒绝编号: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);
});

【问题讨论】:

  • 你从不在任何地方使用entry
  • 方法和数据属性不能同时命名为stop

标签: javascript node.js async-await


【解决方案1】:

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

async getData(entry) {
    if (this.stop) {
        ^^^^

只有在 try/catch 块中使用 return await 才有意义。否则,完全是多余的。

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

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

【讨论】:

    【解决方案2】:

    您的原始代码引用了其他方法,而不是您班级中的方法:

    async getData(entry) {
        if (stop) {  // <--- this refers to this.stop() method
            console.log("Stopped")
            return;
        }
    
        return await get(); <--- this doesn't refer to your `this.get()` method
    }
    

    所以,添加this. 将其固定在以上两个位置。

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2014-10-06
      • 2020-03-23
      • 2023-03-02
      • 1970-01-01
      • 2021-04-03
      • 2020-03-29
      • 2016-04-13
      • 2018-05-16
      相关资源
      最近更新 更多