是否可以等待javascript中的课程?

xaa*_*er1 3 javascript node.js

关键字await使JavaScript等待该承诺完成并返回其结果。

我注意到它可能对await一个功能

var neonlight = await neon();
Run Code Online (Sandbox Code Playgroud)

有可能await上课吗?

var neonlight = await new Neon(neon_gas);
Run Code Online (Sandbox Code Playgroud)

Tak*_*aki 6

从技术上讲..是的,如果构造函数返回a Promise,并且只要awaitasync函数内部,只要这是一个示例(可能不是最好的,实际上让构造函数返回Promise是一种不好的做法,但这仅仅是为了得到这个去工作 ):

class Test {
  constructor() {
    return new Promise((res, rej) => {      
      this.getData().then(({userId, title}) => {
        this.userId = userId;
        this.title = title;
        
        res(this);
      });
    });
  }
  
  getData(){
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())      
  }
  
  greet(){    
    console.log('hello');
  }
}


(async() => {
  const x = await new Test();
  console.log(x.userId, ' : ', x.title);
})();
Run Code Online (Sandbox Code Playgroud)

  • “应该?这是javascript!任何东西都可以是任何东西 (2认同)
  • @crashmstr您可以使用this来解决承诺:res(this)拥有Test而不是hello,我想不出真正的用例,但是.. *从技术上讲,这是可能的* (2认同)