Javascript:使用诺言时的奇怪行为,异步等待,返回“诺言<pending>”

时间:2020-05-07 17:57:50

标签: javascript promise async-await

给出以下代码:

  async #token() {
    const value = await this.belcorp.getAccessToken();
    console.log(value);
  }

此代码返回: enter image description here

但是,如果我尝试使用以下代码在构造函数中返回相同的结果:

constructor() {
    const token = this.#token();
    console.log(token);
  }

  async #token() {
    return await this.belcorp.getAccessToken();
  }

返回以下内容: enter image description here

我该怎么做才能只检索先前的对象?

2 个答案:

答案 0 :(得分:0)

除了构造函数中的Promises问题外,您的代码还返回Promise,因为这是您告诉它要做的事情:const ObjY = [{ id:1, name: "category" }, { id:2, name:"category2" }, { id:3, name:"category3" }]; 函数还返回Promises。如果您想要等待的Promise结果,请将行更改为

async

当然,在这种情况下,您需要使构造函数异步,因此您需要将代码移到构造函数之外。

答案 1 :(得分:0)

您无法创建课程constructor async。相反,只需创建自己的静态构造方法-

class MyThing {
  constructor(token) { // cannot be async
    this.token = token // make sync instead
  }

  static async token() { // make static
    return new Promise(r =>
      setTimeout(r, 1000, "tkn123") // demo token response
    )
  }
  
  static async new () { // make async constructor
    return new MyThing(await this.token()) // await token
  }
}

const main = async () =>
{ console.log("loading...")
  const x = await MyThing.new() // <-- MyThing.new()
  console.log("got token:", x.token)
  return "done"
}

main().then(console.log, console.error)
// loading...
// got token: tkn123
// done