异步/等待需要捕获的承诺?

时间:2018-03-26 10:15:42

标签: javascript ecmascript-6 promise async-await es6-promise

花了一天调试奇怪的错误。我显然不是使用async / await的高手,正如这个小例子所示。我想这对我来说是违反直觉的,但我没有预料到以下情况:

var p = new Promise((resolve, reject) => {
   reject(new Error('some rainy days...'))
})

p
   .then(data => {console.info('data', data)})
   .catch(error => {console.error('inner error', error)})
   .finally(() => {console.info('inner done!')})
   .catch(error => {console.error('outer error', error)})
   .finally(() => {console.info('outer done!')})

async function test (p) {
   try {
      let data = await p
      console.info('async data', data)
      return data
   } catch (error) {
      console.error('async error', error)
      throw error
   } finally {
      console.info('async is done!')
   }
}

test(p)
   .then(data => {console.info('test data', data)})
   .catch(error => {console.error('test error', error)})
   .finally(() => {console.info('test done!')})

输出如下:

inner error Error: some rainy days...
    at Promise (<anonymous>:2:11)
    at new Promise (<anonymous>)
    at <anonymous>:1:9
inner done!
async error Error: some rainy days...
    at Promise (<anonymous>:2:11)
    at new Promise (<anonymous>)
    at <anonymous>:1:9
async is done!
test error Error: some rainy days...
    at Promise (<anonymous>:2:11)
    at new Promise (<anonymous>)
    at <anonymous>:1:9
test done!
outer done!

输出并非意外。但是,我不希望在.catch方法之前和之内使用async。如果我省略所有.catch,则会抛出UnhandledPromiseRejectionWarning。代码如下:

var p = new Promise((resolve, reject) => {
   reject(new Error('some rainy days...'))
})

p
   .then(data => {console.info('data', data)})
   // .catch(error => {console.error('inner error', error)})
   .finally(() => {console.info('inner done!')})
   // .catch(error => {console.error('outer error', error)})
   .finally(() => {console.info('outer done!')})

async function test (p) {
   try {
      let data = await p
      console.info('async data', data)
      return data
   } catch (error) {
      console.error('async error', error)
      throw error
   } finally {
      console.info('async is done!')
   }
}

test(p)
   .then(data => {console.info('test data', data)})
   .catch(error => {console.error('test error', error)})
   .finally(() => {console.info('test done!')})

输出结果为:

async error Error: some rainy days...
    at Promise (<anonymous>:2:11)
    at new Promise (<anonymous>)
    at <anonymous>:1:9
async is done!
outer done!
test error Error: some rainy days...
    at Promise (<anonymous>:2:11)
    at new Promise (<anonymous>)
    at <anonymous>:1:9
test done!
Uncaught (in promise) Error: some rainy days...
    at Promise (<anonymous>:2:11)
    at new Promise (<anonymous>)
    at <anonymous>:1:9

我的期望是await将解包或捕获并抛出错误,该错误将自动捕获到try/catch函数的async块内。否则,我不确定当某些方法可以是promises或scalars时,处理async方法的参数的最佳方法是什么。

显然,我有一些非常错误的东西!如果有人能直接为我创下纪录,我将非常感激!

0 个答案:

没有答案