gpt4 book ai didi

javascript - promise 异步/等待

转载 作者:行者123 更新时间:2023-11-29 10:06:44 26 4
gpt4 key购买 nike

我有以下代码。

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 重写它吗?

最佳答案

据我所知,您不能将构造函数声明为异步函数。但是,您可以从构造函数返回一个 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
})();

关于javascript - promise 异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41937541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com