在Node中相互调用两个Promises

时间:2019-01-05 21:19:37

标签: javascript mysql node.js asynchronous

所以我有一个MySQL查询,需要在以下格式的另一个MySQL查询中调用:

var sql = "some sql code";

    const queryResult = await new Promise((resolve) => {
      connection.query(sql, (err, rows, fields) => {

        // do some stuff here

        var secondSql = "Another sql command";

        const queryTwo = await new Promise((resolve) => {
          connection.query(secondSql, (err, rows, fields) => {

            // do some more stuff
            resolve(something);

        )});

         resovle(something);
      }
  )});

但是,当我尝试运行此代码时,我不断收到错误消息:

"errorMessage": "await is only valid in async function",
"errorType": "SyntaxError",

我知道这与“ await new Promise((resolve)=> {”)没有同步有关,但是我该如何解决才能真正运行呢?我以前只是在代码之外插入了一个异步函数并在我有第二个SQL查询的地方调用它,但是由于某种原因在AWS Lambdas中不起作用。

有人可以告诉我另一种方法吗?

2 个答案:

答案 0 :(得分:0)

为了等待工作,必须从异步函数内部调用它。试试这个:

var sql = "some sql code";

const queryResult = await new Promise((resolve) => {
  connection.query(sql, async (err, rows, fields) => {

    // do some stuff here

    var secondSql = "Another sql command";

    const queryTwo = await new Promise((resolve) => {
      connection.query(secondSql, (err, rows, fields) => {

        // do some more stuff
        resolve(something);

    )});

     resolve(something);
  }
)});

答案 1 :(得分:0)

您可以尝试以下方法:

const sql1 = 'some sql code';
const sql2 = 'Another sql command';

const query1 = () => {
  return new Promise((resolve) => {
    connection.query(sql1, (err, rows, fields) => {
      resolve('something')
    });
  })
};

const query2 = () => {
  return new Promise((resolve) => {
    connection.query(sql2, (err, rows, fields) => {
      resolve('something')
    });
  })
};

[query1, query2].forEach(async request => {
  await request();
});