提问者:小点点

在以下代码中使用ASYN/AWAIT的最佳方法


我是Javascript的新手,我想连接到DB并运行一个脚本。然后得到脚本的结果,按顺序运行函数。如果其中一个函数有任何错误,它应该停止并且不运行其他函数。

我尝试了以下操作:

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

共2个答案

匿名用户

您调用的所有函数都是async,因此返回承诺,应该等待。您可以在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{
        let result = await data()
        result = await func1(result)
        await func2()
        await func3(result)
    } catch(err) {
      console.log(err)
    }
})();

Await Promission.ALL([data,func1,func2,func3])如果其中一个承诺失败,也会失败,但不保证执行顺序。

匿名用户

下面是如果你必须使用try catch在你的每个函数体里面。如果不是,那么我会坚持上面Jeremy的答案。

您可以做的是,不是控制台记录您在try.catch块中接收到的错误,而是抛出新的错误,这将停止代码的执行,并在控制台记录实际的错误。(不完全是控制台日志,而是console.error()it)

这将阻止其他函数的执行,除非您对您的错误做了一些事情(根据错误进行一些可以执行另一个代码的错误处理)。

通常,其语法如下所示:

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

对象err具有一些附加属性,例如namemessage。下面是关于错误对象的更多信息。