我有以下代码。
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重写它?
答案 0 :(得分:3)
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
})();
答案 1 :(得分:1)
你无法完全避免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);
}
如果您愿意,可以将该功能移到课堂上,但我看不出任何理由:
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);
}
}