目前,我正在尝试在类构造函数中使用async/await。这样我就可以为我正在进行的Electron项目获得一个自定义的电子邮件标签。

customElements.define('e-mail', class extends HTMLElement {
  async constructor() {
    super()

    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
  }
})

然而,目前项目不工作,有以下错误:

Class constructor may not be an async method

是否有一种方法来规避这一点,以便我可以使用异步/等待在这?而不是要求回调或.then()?


当前回答

您可以立即调用一个返回消息的匿名异步函数,并将其设置为message变量。如果您不熟悉这种模式,您可能想看看立即调用的函数表达式(IEFES)。这将非常有效。

var message = (async function() { return await grabUID(uid) })()

其他回答

这是可以做到的。 一个简单的代码:

class test
{
   constructor ()
   {
      return new Promise ( (resolve, reject) => { resolve(this); });
   }
   doHello() {console.log("hello");}
}
async function main()
{
   let t = await new test(); //invoking synchronously
   t.doHello(); //t is not a pormise
}
main();

或与上面相同,但添加了实际延迟,使用setTimeout

class test
{
   constructor ()
   {
      return new Promise ( (resolve, reject) =>
      {
         setTimeout (resolve, 5, this);
      });
   }
   doHello() {console.log("hello");}
}
async function main()
{  
   let t = new test(); //now t is a promise
   t.then((a)=>{ a.doHello();}); //a is the real reference to test instance
   console.log("testing"); //"testing" will be printed 5 seconds before "hello"
}
main();

这里是我在现实生活中的一段代码,使用异步图像加载:

class HeightMap extends GlVAObject
{
   #vertices = [];
   constructor (src, crossOrigin = "")
   {
      //super(theContextSetup);
      let image = new Image();
      image.src = src;
      image.crossOrigin = crossOrigin;
      return new Promise ( (resolve, reject) =>
         {
            image.addEventListener('load',  () =>
            {
               //reading pixel values from image into this.#vertices
               //and generate a heights map
               //...
               resolve(this);
            } );
         });
   }
///...
}
async function main()
{
   let vao = await new HeightMap ("./heightmaps/ArisonaCraterHeightMap.png");
///...
}
main();

我根据@Downgoat的回答制作了这个测试用例。 它运行在NodeJS上。 这是Downgoat的代码,其中异步部分由setTimeout()调用提供。

'use strict';
const util = require( 'util' );

class AsyncConstructor{

  constructor( lapse ){
    this.qqq = 'QQQ';
    this.lapse = lapse;
    return ( async ( lapse ) => {
      await this.delay( lapse );
      return this;
    })( lapse );
  }

  async delay(ms) {
    return await new Promise(resolve => setTimeout(resolve, ms));
  }

}

let run = async ( millis ) => {
  // Instatiate with await, inside an async function
  let asyncConstructed = await new AsyncConstructor( millis );
  console.log( 'AsyncConstructor: ' + util.inspect( asyncConstructed ));
};

run( 777 );

我的用例是web应用程序服务器端的dao。 当我看到dao时,它们每个都关联到一个记录格式,在我的例子中是一个MongoDB集合,例如一个厨师。 cooksDAO实例保存厨师的数据。 在我不安的思绪中,我将能够实例化一个cook的DAO,并提供cookId作为参数,实例化将创建对象并使用cook的数据填充它。 因此需要在构造函数中运行异步的东西。 我想写:

let cook = new cooksDAO( '12345' );  

来拥有可用的属性,如cook.getDisplayName()。 有了这个解决方案,我必须做:

let cook = await new cooksDAO( '12345' );  

这和理想情况非常相似。 此外,我需要在一个异步函数中做到这一点。

我的b计划是把数据加载放在构造函数之外,基于@slebetman的建议使用init函数,并像这样做:

let cook = new cooksDAO( '12345' );  
async cook.getData();

这并不违反规则。

你可以使用Proxy的构造句柄来做到这一点,代码如下:

const SomeClass = new Proxy(class A {
  constructor(user) {
    this.user = user;
  }
}, {
  async construct(target, args, newTarget) {
    const [name] = args;
    // you can use await in here
    const user = await fetch(name);
    // invoke new A here
    return new target(user);
  }
});

const a = await new SomeClass('cage');
console.log(a.user); // user info

我通常更喜欢返回一个新实例的静态异步方法,但这里有另一种方法。它更接近于字面上的等待构造函数。它与TypeScript一起工作。

class Foo {
  #promiseReady;

  constructor() {
    this.#promiseReady = this.#init();
  }

  async #init() {
    await someAsyncStuff();
    return this;

  }

  ready() {
    return this.promiseReady;
  }
}
let foo = await new Foo().ready();

这是行不通的。

async关键字允许await在标记为async的函数中使用,但它也将该函数转换为promise生成器。因此,标记为async的函数将返回一个promise。另一方面,构造函数返回它正在构造的对象。因此,我们有这样一种情况,您希望同时返回一个对象和一个承诺:这是不可能的情况。

你只能在可以使用承诺的地方使用async/await,因为它们本质上是承诺的语法糖。不能在构造函数中使用promise,因为构造函数必须返回要构造的对象,而不是promise。

有两种设计模式可以克服这个问题,它们都是在承诺出现之前发明的。

使用init()函数。这有点像jQuery的.ready()。你创建的对象只能在它自己的init或ready函数中使用:

用法:

    var myObj = new myClass();
    myObj.init(function() {
        // inside here you can use myObj
    });

实现:

    class myClass {
        constructor () {

        }

        init (callback) {
            // do something async and call the callback:
            callback.bind(this)();
        }
    }

使用构建器。我在javascript中没有见过这种方法,但当需要异步构造对象时,这是Java中更常见的解决方法之一。当然,在构造需要大量复杂参数的对象时,会使用构建器模式。这正是异步构建器的用例。区别在于异步构建器不返回对象,而是返回该对象的承诺:

用法:

    myClass.build().then(function(myObj) {
        // myObj is returned by the promise, 
        // not by the constructor
        // or builder
    });

    // with async/await:

    async function foo () {
        var myObj = await myClass.build();
    }

实现:

    class myClass {
        constructor (async_param) {
            if (typeof async_param === 'undefined') {
                throw new Error('Cannot be called directly');
            }
        }

        static build () {
            return doSomeAsyncStuff()
               .then(function(async_result){
                   return new myClass(async_result);
               });
        }
    }

使用async/await实现:

    class myClass {
        constructor (async_param) {
            if (typeof async_param === 'undefined') {
                throw new Error('Cannot be called directly');
            }
        }

        static async build () {
            var async_result = await doSomeAsyncStuff();
            return new myClass(async_result);
        }
    }

注意:虽然在上面的例子中,我们为异步构建器使用了promise,但严格来说它们并不是必需的。您也可以轻松地编写一个接受回调的构建器。


注意在静态函数中调用函数。

这与异步构造函数没有任何关系,而是与关键字This的实际含义有关(对于来自自动解析方法名的语言的人来说,这可能有点令人惊讶,即不需要This关键字的语言)。

this关键字引用实例化的对象。不是这门课。因此,你通常不能在静态函数内部使用它,因为静态函数不绑定到任何对象,而是直接绑定到类。

也就是说,在下面的代码中:

class A {
    static foo () {}
}

你不能:

var a = new A();
a.foo() // NOPE!!

相反,你需要调用它为:

A.foo();

因此,下面的代码将导致错误:

class A {
    static foo () {
        this.bar(); // you are calling this as static
                    // so bar is undefinned
    }
    bar () {}
}

要修复它,你可以将bar设置为常规函数或静态方法:

function bar1 () {}

class A {
    static foo () {
        bar1();   // this is OK
        A.bar2(); // this is OK
    }

    static bar2 () {}
}