簡體   English   中英

Javascript:使用承諾時的奇怪行為,異步等待,返回“承諾<pending> ”</pending>

[英]Javascript: Strange behavior when using promises, async-await, returns “Promise <pending>”

給定以下代碼:

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

此代碼返回: 在此處輸入圖像描述

但是,如果我嘗試使用以下代碼在構造函數中返回相同的結果:

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

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

返回以下內容: 在此處輸入圖像描述

我應該怎么做才能只檢索以前的 object?

除了構造函數中的 Promises 問題之外,您的代碼返回 Promise 因為這是您告訴它要做的: async函數返回 Promises。 如果您想要等待的 Promise 結果,請將行更改為

const token = await this.#token();

當然,在這種情況下,您需要構造函數是異步的,因此您需要將代碼移到構造函數之外。

您不能使 class constructor async 相反,只需制作自己的 static 構造函數方法 -

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM