【问题标题】:Node / Mysql async datasNode / Mysql 异步数据
【发布时间】:2020-06-15 02:19:06
【问题描述】:

我想按顺序(一、二、三、四)查看消息。 因为目前我的脚本不起作用,因为请求没有时间完成。

此时代码返回一三四二 我认为这是问题,因为我不使用 async 和 await 但我不明白在哪里以及如何使用

function dropAll() {
  console.log("ONE");

  db.query("SHOW tables", (err, result) => {
    result.map(async list => {
      db.query(`DROP TABLE \`${list.Tables_in_gcd_updt}\``, (err, results) => {
        console.log(list.Tables_in_gcd_updt + " REMOVED");

        console.log("TWO");
      });
    });
  });
}

function getAll() {
  console.log("FOUR");
}

const infiniteQuestion = function() {
  prompt.question("What do you want to your DB project ?", answer => {
    switch (answer) {
      case "drop":
        dropAll();
        console.log("THREE");
        getAll();
        infiniteQuestion();
        break;
      case "exit":
        console.log(`${answer} unknow`);
        rl.close();
        process.exit(0);
      default:
        infiniteQuestion();
    }
  });
};

infiniteQuestion();

谢谢

【问题讨论】:

标签: javascript mysql node.js async-await


【解决方案1】:

如您所想,这里需要使用 async/await,因为您的 dropAll 方法的执行是异步的。

您可以参考这个documentation 来了解应该如何使用 async/await。

您的示例可以更新为以下内容:

function promisifyQuery(query) {
  return new Promise((resolve, reject) =>
    db.query(query, async (err, result) => {
      if (err) {
        reject(err)
      } else {
        resolve(result)
      }
    })
  )
}

async function dropAll() {
  console.log("ONE");
  const result = await promisifyQuery("SHOW tables")

  return Promise.all(result.map(async list => {
    await promisifyQuery(`DROP TABLE \`${list.Tables_in_gcd_updt}\``)
    console.log(list.Tables_in_gcd_updt + " REMOVED");

    console.log("TWO");
  }));
}

function getAll() {
  console.log("FOUR");
}

const infiniteQuestion = async function () {
  await prompt.question("What do you want to your DB project ?", async answer => {
    switch (answer) {
      case "drop":
        await dropAll();
        console.log("THREE");
        getAll();
        return infiniteQuestion();
      case "exit":
        console.log(`${answer} unknow`);
        rl.close();
        process.exit(0);
      default:
        return infiniteQuestion();
    }
  });
};

infiniteQuestion();

【讨论】:

  • await 前面的db.query("SHOW tables", async (err, result) => { 没有任何意义。如果一个函数接受并接收到(err, result) 回调,那么它不太可能返回一个 Promise。 result.map(async list => { 前面的 await 没有任何意义,因为 map 中的回调没有返回有意义的 Promise。
【解决方案2】:

如果您想在执行异步第二个函数/指令之前等待第一个异步函数/指令完成,您应该将第二个函数/指令放在第一个回调中。你最终会得到一个嵌套的回调。使用 Promise 的代码演示。


    function foo1()
      .then(el12 => {
        //logic for foo1
        function foo2()
          .then(ele2 => {
          //logic for foo2})
        })
    })

第二个选项是使用异步/等待。

async function main(){
   await function foo1()
   await function foo2()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2015-01-13
    • 2018-05-15
    • 1970-01-01
    • 2020-06-01
    相关资源
    最近更新 更多