![](/img/trans.png)
[英]Getting 'Promise { <pending> }' message when using async-await to perform tcp client
[英]Javascript: Strange behavior when using promises, async-await, returns “Promise <pending>”
除了構造函數中的 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.