javascript - 方法异步时如何存储从数据库返回的值
问题描述
我是 node/js 的新手,我想知道我应该怎么做才能修复我的数据库调用。目前,调用会从我的 Postgres DB 返回所有数据,但是当我尝试存储它时,尚未返回值。我应该如何构建我的代码,以便我可以等到值被存储,以便当该信息传递给下一个变量时它可用?如果您看下面,您可以看到该returnedOrders
字段将具有该undefined
值,因为在填充之前仍在从 db 中获取该值。
function insertOrder() {
dbConnector.connectToDB();
const returnedOrders = await dbConnector.retrieveAllOrders();
console.log("The returned orders" , returnedOrders);
}
function connectToDB() {
conn.connect().then((success, error) => {
if(error) {
console.log(`There was an error connecting because: ${error}`);
}else {
console.log(`Successfully connected to the database: ${success}`);
}
});
}
function retrieveAllOrders(){
const query = `SELECT * from food.pizza`;
conn.query(query).then((results, error) => {
if(error) {
console.log(`There was an error due to: ${error}`);
return;
}
console.log("Successfully connected. Running first query");
console.log(`Results are: ${JSON.stringify(results.rows[0], null , 2)}}`)
conn.end();
return results;
})
.catch((error) => {
console.log(`Unable to retrieve query due to: ${error.message}`)
})
}
这是我的终端的输出。在这里你可以看到事情发生的顺序
node app.js
The returned orders undefined
Successfully connected to the database: [object Object]
Successfully connected. Running first query
Results are: { Here will be the results from the database. }
解决方案
推荐阅读
- sql - 如何从列中提取特定文本
- xcode - 在 CollectionView Swift5 中显示 OtherScreen CellImage
- c# - C# XmlSerializer DefaultAttribute 属性仍然为 nullables 序列化
- flutter - MissingPluginException(MissingPluginException(在通道 dexterx.dev/trail 上找不到方法 getTimeZoneName 的实现))
- swift - 使用带有套接字 IO 的 iOS (Swift) 客户端加入 Laravel Echo 通道
- nuxeo - 使用 nuxeo 平台创建新文档时出现“未捕获的 TypeError:无法读取属性 'replace' of null”错误
- python - 反应日志显示消息作者的姓名,而不是反应的人(discord.py)
- maven - 子模块 ear 上提供的 Maven 依赖项抛出 ClassNotFoundException
- spring-boot - Spring Boot,Hibernate,JPA中关系@ManyToOne的问题
- javascript - npm 包转储代码库的域模型?