0

Looking at the correct/best/better way to use AWAIT with MySQL2 in a Node.js/Express.js app when I need to run multiple queries in a single request.

Early on in my app I create a Promise Pool from my Database config

const promisePool = db.promise();

Then, on a POST request I accept 2 values, both of which I need to verify are valid, and then take the returned ID's and INSERT them in to another table.

Below is was my first attempt but I am missing out on the JS's concurrently goodness. (I've overly simplified all the calls/SQL for demonstration purposes),

app.post('/addUserToDepartment', async (req, res) => {
    // Get the POST variables
    let email = 'example@example.com';
    let departmentname = 'sales';
    let insertParams = [];

    // Need to check if Department ID is even valid
    const [departments] = await promisePool.query( "SELECT ? AS deptid", [departmentname] );

    // Need to check if Email address is valid
    const [user] = await promisePool.query( "SELECT ? AS userid", [email] );

    // This would normall be an INSERT or UPDATE statement
    if(departments.length && user.length){
        const [rows] = await promisePool.query( "SELECT ? AS passedDeptId,? AS passedUserid", [departments[0].deptid, user[0].userid] );
    }

    res.send( rows )
}

Here is my second stab at it, now wrapping the promises up.

app.post('/addUserToDepartment', async (req, res) => {
    // Get the POST variables
    let email = 'example@example.com';
    let departmentname = 'sales';
    let insertParams = [];

    // Need to check if Department ID is even valid
    let [[departments],[user]] =
    await Promise.all([
        promisePool.query( "SELECT ? AS deptid", [departmentname] ),
        promisePool.query( "SELECT ? AS userid", [email] )
    ])

    // This would normall be an INSERT or UPDATE statement
    if(departments.length && user.length){
        let [rows] = await promisePool.query( "SELECT ? AS passedDeptId,? AS passedUserid", [departments[0].deptid, user[0].userid] );
    }

    res.send( rows )
}

The IF at the end still doesn't 'feel' right, but I need to know that the first two queries are valid otherwise I'll send the user to an error page.

What would be a better way to achieve the above result without forfeiting readability too much?

4

2 回答 2

1

首先:两个片段都被破坏了,因为rows变量需要在 if 之外声明if

除此之外,您所做的大部分都很好,但这里的大问题是,如果length其中一个为 0,则您什么也不返回。

这真的是你想要的行为吗?如果我打电话给/addUserToDepartment你的数据库有问题,你想让它静默失败吗?

我认为更好的方法是在出现问题时返回适当的错误。理想情况下,您应该只抛出一个异常,(但您使用的是 Express,我不确定它们是否支持捕获异常)。

于 2018-11-01T16:47:59.227 回答
0

这是我最后的结果。我添加了捕获,我还将最后一个查询作为 Promise.all() 链的一部分。

  app.get('/test2', async (req, res) => {
    // Get the POST variables
    let email = 'example@example.com';
    let departmentname = 'sales';
    let insertParams = [];
    let rtn = {
      status : '',
      errors : [],
      values : []
    }
    console.clear();
    // Need to check if Department ID is even valid

    let arrayOfPromises = [
      promisePool.query( "SELECT ? AS did", [departmentname] ),
      promisePool.query( "SELECT ? AS uid", [email] )
    ]
    await Promise.all(arrayOfPromises)
    .then( ([d,u] ) => {
      // Get the  values back from the queries
      let did = d[0][0].did;
      let uid = u[0][0].uid;
      let arrayOfValues = [did,uid];

      // Check the values
      if(did == 'sales'){
        rtn.values.push( did );
      } else{
        rtn.errors.push( `${did} is not a valid department`);
      }
      if(uid == 'example@example.com'){
        rtn.values.push( uid );
      } else{
        rtn.errors.push( `${did} is not a valid department`);
      }

      if( rtn.errors.length === 0){
        return arrayOfValues;
      } else{
        return Promise.reject();
      }
    })
    .then( async ( val ) => {
      // By this point everything is ok
      let [rows] = await promisePool.query( "SELECT ? AS passedDeptId,? AS passedUserid", val );
      res.send( rtn )
    })
    .catch((err) => {
      console.error(err)
      rtn.status = 'APPLICATION ERROR';
      rtn.errors.push( err.message);
      res.send( rtn )
    });
  });
于 2018-11-07T16:18:16.167 回答