对NodeJs MySQL驱动程序使用异步

时间:2019-05-21 16:13:41

标签: javascript node.js asynchronous async-await

我想将函数router.get('/', etc)重构为使用 async await 的函数。 res.sendconnection.query让我不知道如何使用异步/等待构造来处理它们。

我尝试使用此功能:

const awaitHandlerFactory = (middleware) => {
    return async (req, res, next) => {
        try {
            await middleware(req, res, next)
        } catch (err) {
            next(err)
        }
    }
};

这是文件中的代码:

var express = require('express');
// const data = require("../data/repo");
var router = express.Router();

let mysql = require("mysql");
let config = require('../config/config.json');

let connection = mysql.createConnection(config);
connection.connect();
//
let guests = {};
let query1 = "select * from guests";
//GET home page.
 router.get('/', function(req, res, next) {
     connection.query(query1,  function (err, rows) {
         guests['guests'] = rows;
         res.send(guests)
     });
 });

此功能可用于router.get('/', etc...)

我明白了:这就是我想要的。

 "guests": [
        {
            "event_id": 1,
            "guest_id": 1,
            "firstName": "lkasjdl;skj",
            "lastName": "lskajdfal;skdj",
            "role": "lsakdjfalskdjflks;adjf",
            "created_at": null,
            "updated_at": null
        },

1 个答案:

答案 0 :(得分:0)

您需要将回调样式的connection.query转换为可以等待的内容。 promisify中的util会做到这一点。

const express = require('express');
// const data = require("../data/repo");
const router = express.Router();

const util = require("util");
const mysql = require("mysql");
const config = require('../config/config.json');

const connection = mysql.createConnection(config);
const query = util.promisify(connection.query);
connection.connect();

const guests = {};
const query1 = "select * from guests";
//GET home page.
 router.get('/', async function(req, res, next) {
    try {
        const rows = await query(query1);
    } catch(ex) {
      //process your error
    }
    guests['guests'] = rows;
    res.send(guests);
 });