简体   繁体   English

在尝试捕获中处理承诺错误第一级

[英]handle promise error first level inside try catch

function testPromise(id) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            if (typeof id === 'number') {
                resolve(id);
            } else {
                reject('error');
            }
        }, 500);
    }
    );
}
async function test(){
  try{
    testPromise(10)
    for(let i=0 ; i<10000; i++){
      ....
    }
    .
    .
  }catch(err){
    console.log(err)
  }
}
test();

ok consider above code I want to run testPromise function asynchronously so if I use await syntax testPromise(10) run first then for loop code run if, I don't use await, testPromise(10) run asynchronously and everything is good up to now, however, if testPromise encounter an error how should I handle it? 好的,考虑上面的代码,我想异步运行testPromise函数,因此,如果我先使用await语法, testPromise(10)运行testPromise(10)然后运行循环代码,如果我不使用await,则testPromise(10)异步运行,并且到目前为止一切都很好但是,如果testPromise遇到错误,我该如何处理? is there any way to use async-await structure and handle this error inside a try-catch structure? 有什么方法可以使用async-await结构并在try-catch结构中处理此错误?
I know I can use catch function testPromise(10).catch(err =>{}); 我知道我可以使用catch函数testPromise(10).catch(err =>{}); to handle error but I want to know is there any way to handle it inside my first level try-catch 处理错误,但我想知道在我的第一级try-catch中有什么方法可以处理错误

You can't. 你不能

You either use try-catch along with await or you use catch on the promise. 您既可以将try-catchawait一起使用,也可以对承诺使用catch

You should take into account that the error could be thrown even when your function ( test ) already finished its execution. 您应该考虑到即使您的函数( test )已经完成其执行,也可能引发该错误。

See @Bergi's answer for a correct example. 有关正确的示例,请参见@Bergi的答案。

If you want to run it concurrently with your loop and properly handle errors from both (which necessarily includes waiting for both), then Promise.all is your only choice: 如果您想在循环中同时运行它并正确处理来自两者的错误(这必然包括等待两者),那么Promise.all是您唯一的选择:

async function test() {
  try {
    await Promise.all([
      testPromise(10),
      (async function() {
        for (let i=0; i<10000; i++) {
          …
        }
        …
      }())
    ]);
  } catch(err) {
    console.log(err);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM