异步并在节点js中等待MySQL调用 [英] async and await on MySQL call in node js

查看:72
本文介绍了异步并在节点js中等待MySQL调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我对节点还很陌生,我刚刚了解了javascript中提供的async和await函数.我正在尝试在下面随附的代码段中实现此方法.以我的理解,数据库响应应该首先打印到控制台,然后完成",但是我无法使其正常工作.任何帮助将不胜感激.

all I'm pretty new to node and I just learned about the async and await function offered in javascript. I'm trying to implement this method in the code snippet attached below. From my understanding, the database response should first print out to the console and then the "done", but I can't get it to work. Any help would be greatly appreciated.

也请尝试说明您所做的修复操作,因为我想了解自己做错了什么.

Please also try to explain what you did to fix it, because I want to understand what I'm doing wrong.

var mysql = require("mysql");
const cTable = require('console.table');

var connection = mysql.createConnection({
    host: "localhost",
    port: 8889,
    user: "root",
    password: "root",
    database: "testDB"
})

connection.connect((err, fields) => {
    if (err) {
        return console.log(err.code);
    }
});

var displayDB = async () => {
    connection.query('SELECT * FROM products', (err, resp) => {
        if (err) {
            return console.log(err.code);
        } else {
            table = [];
            resp.forEach((product) => {
                obj = {
                    'Product ID': product.productID,
                    'Category': product.category,
                    'Price': product.price,
                    'Stock': product.stockQuantity
                }
                table.push(obj)
            })
            console.table(table)
            connection.end()
        }
    })
}

var test = async () => {
    var x = await displayDB()
    console.log('done')
}
test()

推荐答案

您的displayDB函数中没有return语句.

通常,这将导致函数返回undefined,但是由于您已声明async,因此它将导致其返回立即已解决的Promise.

Normally this would cause a function to return undefined, but because you declared it async, it causes it to return a Promise that is immediately resolved.

如果希望它等待数据库查询完成,则需要明确返回new Promise,准备就绪后返回 resolve(即在您拨打connection.end()之后).

If you want it to wait until the database query is complete, then you need to explicitly return a new Promise which you resolve when you are ready (i.e. after you have called connection.end()).

这篇关于异步并在节点js中等待MySQL调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆