【问题标题】:Select updated row immediately after updating the row using Promise.all()使用 Promise.all() 更新行后立即选择更新的行
【发布时间】:2020-12-12 19:05:16
【问题描述】:

我的目标是立即使用promise.all()select 更新的行。我正在使用promise.all(),因为我认为如何绕过node.js 异步行已成功更新,但select 语句没有返回任何内容。我正在使用 mysql 数据库。我将不胜感激任何帮助。谢谢。

const query = promisify(db.query.bind(db));
Promise.all( [query("UPDATE order_detail SET tracking_number = '2323211' where order_detail_id = 81")])
.then(() => query('select * from order_detail where order_detail_id = ?', [81]))
.then(data => {
   console.log(data);
})

【问题讨论】:

  • 如果你只有一个承诺,为什么要使用Promise.all?
  • @eol 我认为这将是我绕过 node.js 异步的一种方式。我也是开放的建议。谢谢。
  • @NaheemOlaniyan wdym 绕过?您也可以使所有异步代码同步(但是会慢得多)
  • @Zer0 我的想法是插入 node.js 后我将无法立即获取数据。请问有没有更好的办法?

标签: javascript node.js


【解决方案1】:

promiseAll() 与 .then 和 async await

使用.then:

const query = promisify(db.query.bind(db));
Promise.all([query("UPDATE order_detail SET tracking_number = '2323211' where order_detail_id = 81")])
    .then(() => {
        query('select * from order_detail where order_detail_id = ?', [81])
          .then((data) => console.log(data));
    });

使用async 和await:

const run = async () => {
    const query = promisify(db.query.bind(db));
    const resultArr = await Promise.all([query("UPDATE order_detail SET tracking_number = '2323211' where order_detail_id = 81")]);
    const result = await query('select * from order_detail where order_detail_id = ?', [81]);
}
run();

【讨论】:

    【解决方案2】:

    你需要在then里面做你的操作

    const query = promisify(db.query.bind(db));
    Promise.all([query("UPDATE order_detail SET tracking_number = '2323211' where order_detail_id = 81")])
      .then(() => {
        query('select * from order_detail where order_detail_id = ?', [81]).then((data) => console.log(data))
      })
    

    【讨论】:

    • @NaheemOlaniyan 这应该现在可以工作了。如果你可以检查一下?
    • 我试图在console.log(data) 之后在.then 内做一些事情,但我得到了一个错误。请问您有什么建议可以解决这个问题吗?
    猜你喜欢
    • 2013-10-15
    • 2021-01-04
    • 2013-05-29
    • 1970-01-01
    • 2020-11-05
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多