在以下代码中使用 asyn/await 的最佳方式

Best way to use asyn/await in the following code

我是 Javascript 的新手,我想连接到数据库和 运行 脚本。然后依次获取脚本和运行函数的结果。 如果其中一项功能有任何错误,它应该停止并且不会 运行 其他功能。

我尝试了以下方法:

const {
  Client
} = require('pg')
const client = new Client({
  'connection info'
})

client.connect()
  .then(() => console.log('DB connected'))
  .catch(err => console.error('connection error', err.stack))

let dbResult

const data = async() => {
  try {
    dbResult = await client.query('SCRIPT') // array of json 
  } catch (error) {
    console.log(error);
  }
}

const func1 = async() => {
  try {
    // do something with dbResult
    console.log('func1 success msg')
  } catch (error) {
    console.log('error in func1')
  }
}

const func2 = async() => {
  try {
    // do something with dbResult
    console.log('func2 success msg')
  } catch (error) {
    console.log('error in func2')
  }
}

const func3 = async() => {
    dbResult.forEach(result => {
    // do something
})
  try {
    // do something with dbResult
    console.log('func3 success msg')
  } catch (error) {
    console.log('error in func3')
  }
}

data()
func1()
func2()
func3()

下面是您是否必须在每个函数体内使用 try catch。如果没有,那么我会坚持上面杰里米的回答。

您可以 throw new error 代替控制台记录您在 try..catch 块中收到的错误,这将停止代码的执行并在控制台记录实际错误。 (好吧,不完全是控制台日志,而是 console.error() 它)

这将阻止其他功能的执行,除非您对错误进行处理(根据错误进行一些错误处理,以便您可以执行其他代码)。

一般来说,语法如下:

try {
  await someStuff();
} catch (err) {
  throw new Error(err)
}

对象 err 有一些额外的属性,例如 namemessage。 这是关于 Error 对象的更多信息。

您调用的所有函数都是 async,因此 return 承诺并应等待。您可以在 try/catch 块中等待所有这些,因此如果一个失败,其他的将不会执行。

不要在每个单独的函数中使用 try/catch,而是在此处使用:

const data = async() => client.query('SCRIPT') // array of json 

const func1 = async() => console.log('func1 success msg')

const func2 = async() => console.log('func2 success msg')

const func3 = async() =>  dbResult.forEach(result => console.log(result))

(async () => {
    try{
        await client.connect();
        let dbResult = await data();
        dbResult = await func1(dbResult);
        await func2();
        await func3(dbResult);
    } catch(err) {
      console.log(err);
    }
})();
如果其中一个 Promise 失败,

await Promise.all([data, func1, func2, func3]) 也会失败,但不保证执行顺序。