Passing in Async functions to Node.js Express.js router

前端 未结 5 2049
别跟我提以往
别跟我提以往 2021-02-04 05:37

This seems like a straightforward google, but I can\'t seem to find the answer...

Can you pass in ES7 async functions to the Express router?

Example:

<         


        
5条回答
  •  -上瘾入骨i
    2021-02-04 06:09

    Use express-promise-router.

    const express = require('express');
    const Router = require('express-promise-router');
    const router = new Router();   
    const mysql = require('mysql2');
    
    const pool = mysql.createPool({
      host: 'localhost',
      user: 'myusername',
      password: 'mypassword',
      database: 'mydb',
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0
    }).promise();
    
    router.get('/some_path', async function(req, res, next) {
      const [rows, ] = await pool.execute(
        'SELECT * ' +
        'FROM mytable ',
        []
      );
    
      res.json(rows);
    });
    
    module.exports = router;
    

    (The above is an example of using mysql2's promise interface with express-promise-router.)

提交回复
热议问题