首页 > 解决方案 > 方法异步时如何存储从数据库返回的值

问题描述

我是 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. }

标签: javascriptnode.jspostgresqlasynchronousnode-postgres

解决方案


推荐阅读