【问题标题】:Sequential calls with nodejs + postgres使用 nodejs + postgres 的顺序调用
【发布时间】:2019-12-16 18:26:37
【问题描述】:

我尝试使用 nodeJS 以顺序方式调用 2 个对 postgres 的查询。我来到了这个代码。 但是我对此并不满意,做一件简单的事情似乎过于复杂。有没有更简单的方法来做我想做的事情?

基本上,我尝试在控制台上打印“before 1st”,然后执行 select now(),然后打印结果,然后写入“after 1st”,然后打印“before 2nd”,然后执行 select now(),然后打印结果,然后写“第二次之后”

getConn().
then(async() => {
  console.log("before 1st selectNow2")
  await selectNow2()
  console.log("after 1st selectNow2")
})
.then(async() => {
  console.log("before 2nd selectNow2")
  await selectNow2()
  console.log("after 2nd selectNow2")
})

async function selectNow2() {
  await client.query('SELECT NOW()')
  .then(res => {
    console.log(res.rows[0])
  })
  .catch(err => {
    console.log(err.stack)
  })
}

【问题讨论】:

    标签: node.js promise async-await sequential


    【解决方案1】:

    您不需要在selectNow2() 内的同一语句中使用awaitthen()。由于您使用的是await,因此您不会返回一个承诺,这意味着返回的值将没有 then() 方法。

    performQuery().then(() => {
      console.log("DONE");
    });
    
    async function performQuery(){
       await getConn();
       console.log("before 1st selectNow2");
       await selectNow2();
       console.log("after 1st selectNow2");
       console.log("before 2nd selectNow2");
       await selectNow2();
       console.log("after 2nd selectNow2");
    }
    
    async function selectNow2) {
      try{
        await client.query('SELECT NOW()');
        console.log(res.rows[0])
      }catch(err){
        console.log(err.stack)
      }
    }
    

    【讨论】:

    • async 函数总是返回一个 promise,所以代码可以工作,我看不出你不能这样做的原因 .then(async ...) Edit: 无论如何代码是好的,但我认为,应该解释为什么它与问题示例相同
    • 我的意思是,如果您使用 await,则不需要链接 .then()
    • 正如他在问题中提到的那样。他的回答是正确的,但需要另一种格式。这就是我所做的。
    • 感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多