Artem Gurzhii
Artem Gurzhii

Reputation: 49

Promise to async/await

I'm having following code.

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

Is there any way to move store function inside the class constructor and rewrite it using async/await?

Upvotes: 3

Views: 849

Answers (2)

Bergi
Bergi

Reputation: 664297

You cannot completely avoid the Promise constructor as you need it for promisifying the connection:

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

With that, you can use 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);
}

If you want, you can move that function into your class, but I don't see any reason for it:

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

Upvotes: 1

nils
nils

Reputation: 27174

AFAIK you can't declare the constructor an async function. You can however return a Promise from the constructor. 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
})();

Upvotes: 3

Related Questions