编程语言
首页 > 编程语言> > javascript-承诺异步/等待

javascript-承诺异步/等待

作者:互联网

我有以下代码.

class DB {
  constructor(client) {
    this.client = client;
  }
}

export default function store() {
  return new Promise((resolve, reject) => {
    pg.connect(process.env.DATABASE_URL, client => {
      client.query('CREATE TABLE x(name VARCHAR(100))');
      return resolve(new DB(client));
    });
  });
}

有什么办法可以在类构造函数中移动存储功能,并使用async / await重写它?

解决方法:

AFAIK,您不能将构造函数声明为异步函数.但是,您可以从构造函数返回Promise. This seems to be a terrible idea, so don’t use this in a real-world context.

// Define the class
class DB {
  constructor() {
    return this.store().then(client => { this.client = client; return this; });
  }

  async store() {
    const client = await new Promise((resolve) => {
      pg.connect(process.env.DATABASE_URL, resolve);
    });
    client.query('CREATE TABLE x(name VARCHAR(100))');
    return new DB(client);
  }
}

// Create an async function environment
(async function handleData() {
  const db = await new DB();
  // Do something with your DB
})();

标签:ecmascript-2017,async-await,javascript
来源: https://codeday.me/bug/20191026/1935407.html