使用 nodejs + postgres 的顺序调用

Sequential calls with nodejs + postgres

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

基本上,我尝试在控制台上打印 "before 1st" 然后执行 select now(),然后打印结果,然后写入 "after 1st",然后打印 "before 2nd"然后执行selectnow(),然后打印结果,然后写入"after 2nd"

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)
  })
}

您不需要在 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)
  }
}