提供 async/await

Promise to async/await

我有以下代码。

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));
    });
  });
}

有什么方法可以将存储函数移动到 class 构造函数中并使用 async/await 重写它?

据我所知,您不能将构造函数声明为异步函数。但是,您可以 return 来自构造函数的 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
})();

您不能完全避免 Promise 构造函数,因为您需要它来保证连接:

function connect(url) {
  return new Promise((resolve, reject) => {
    pg.connect(url, resolve);
  });
}

这样,您可以使用 async/await:

export default async function store() {
  const client = await connect(process.env.DATABASE_URL);
  client.query('CREATE TABLE x(name VARCHAR(100))');
  return new DB(client);
}

如果需要,您可以将该功能移到您的 class 中,但我看不出有任何理由这样做:

export default class DB {
  constructor(client) {
    this.client = client;
  }
  static async store() {
    const client = await connect(process.env.DATABASE_URL);
    client.query('CREATE TABLE x(name VARCHAR(100))');
    return new this(client);
  }
}