简体   繁体   English

处理Js承诺拒绝

[英]Handling Js promise rejection

How do you handle an error (eg. "new error" below) that is outside of the promise? 你如何处理承诺之外的错误(例如下面的“新错误”)?

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

testError().catch(err => {
        return err;  // code doesn't come here
    })
    .then(ok => {
        console.log(ok)
    });

If you're not sure whether a function will throw (or return a value) synchronously, you can call it using .then() . 如果您不确定某个函数是否会同步抛出(或返回一个值),您可以使用.then()调用它。 This will wrap it so that the result will be handled consistently no matter how it is produced: 这将包装它,以便无论如何生成结果都将得到一致的处理:

 function testError() { throw new Error("new error") // how to handle this? var p123 = new Promise(function(resolve, reject) { resolve(123) }); return p123 }; Promise.resolve() .then(testError) .catch(err => { console.error(err); return err; }) .then(ok => { console.log(ok.message) }); 

Since the error doesn't involve the async code, a regular try-catch should do fine here: 由于错误不涉及异步代码,因此常规try-catch应该在这里做得很好:

try {
  testError().catch(err => {
    return err;  // code doesn't come here
  })
  .then(ok => {
     console.log(ok)
  });
}
catch(e) {
   // 
}

Note that when the async-await pattern finally becomes the native way of resolving promises, the try-catch will also become the native way of handling errors: 请注意,当async-await模式最终成为解析promise的本机方式时, try-catch也将成为处理错误的本机方式:

try {
    var ok = await testError();
    console.log(ok)
}
catch(e) {
    console.log('e:' +e);
}

As one can easily verify, this one correctly handles both the sync and the async error and is much cleaner than then-catch . 可以轻松验证,这个正确处理同步和异步错误,并且比then-catch更清晰。

Since the error is thrown outside of the promises, you cannot catch it using a promise catch statement. 由于错误是在promises之外抛出的,因此无法使用promise catch语句捕获它。

You can use a try/catch to catch the error instead. 您可以使用try / catch来捕获错误。

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

try {
  testError().then(ok => {
    console.log(ok)
  });
} catch (err) {
  console.log(err.message);
}

If you can, rewrite your testError function like so 如果可以的话,重写你的testError函数就好了

 function testError () { return new Promise(function (resolve, reject) { throw new Error('new error') resolve(123) }) } testError().then(ok => console.log(ok), err => console.error(err.message)) 

  1. Run it once to see it throw the error in console.error 运行一次,看它在console.error抛出错误
  2. Comment out the throw line to see the promise resolve successfully 注释掉throw线以查看承诺成功解决

You rewrite it, because making a caller check for both exceptions and rejections is an anti-pattern: 你重写它,因为调用者检查异常和拒绝是一种反模式:

 function testError() { return Promise.resolve().then(() => { throw new Error("new error"); // rejects returned promise return new Promise(function(resolve) { resolve(123); }); }); } testError().catch(err => console.log("Caught " + err)); 

This is implicit with async functions; 这是async函数隐含的; they always return a promise: 他们总是回应一个承诺:

 async function testError() { throw new Error("new error"); // rejects implicit promise return await new Promise(function(resolve) { resolve(123); }); } testError().catch(err => console.log("Caught " + err)); 

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

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