![](/img/trans.png)
[英]What's the correct way to handle promise rejections so that the function exits?
[英]What is the correct way to ONLY handle a promise error?
請參見下面的示例,其中method將返回一個Promise並相應地解析/拒絕該Promise。 我目前不希望解決該問題,我只想處理拒絕問題。
有沒有一種更好的,跨瀏覽器的方法而不聲明沒有用的成功功能?
MyClass.method().then((sData) => {
// Nothing to do here
}, (eData) => {
// Important code to run here
})
在我的代碼中,我正在使用AngularJS promises。 但是,該問題與其他常見庫和本機Promise對象有關。
是! 您可以為此使用catch
函數:
MyClass.method()
.catch(error => { ... })
假設MyClass.method()
返回有效的Promise API對象, catch
應該能夠捕獲任何拒絕。
在其他答案狀態下,請使用.catch
函數。
MyClass.method()
.catch(error => { error handling logic (async)})
我要添加的內容如下:
通常,在.then()
函數中,您提供了2個這樣的回調(這些回調將始終異步執行):
const promise2 = doSomething().then(successCallback, failureCallback);
然而.catch()
的簡寫為then()
在successCallback由被填充null
。
then(null, failureCallback)
YourClass.method().catch(錯誤=> {...})
參見參考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
您可以使用Promise的.catch
方法。
MyClass.method().catch(error => {
// handle the error here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.