我想将函数router.get('/', etc)
重构为使用 async 和 await 的函数。 res.send
和connection.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
},
答案 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);
});