簡體   English   中英

如何.catch Promise.reject

[英]How to .catch a Promise.reject

我有一個輔助函數,用於在 CouchDB 中使用fetch ,其結尾為:

...
return fetch(...)
  .then(resp => resp.ok ? resp.json() : Promise.reject(resp))
  .then(json => json.error ? Promise.reject(json) : json)

當我在其他地方使用它時,我的印象是我可以.catch那些明確的拒絕:

  above_function(its_options)
    .then(do_something)
    .catch(err => do_something_with_the_json_error_rejection_or_resp_not_ok_rejection_or_the_above(err))

但唉,我似乎無法控制拒絕。 我遇到的具體錯誤是 HTTP 401 響應。

什么給?

(請注意,有隱含的ES6 return的中.then S)

 function test() { return new Promise((resolve, reject) => { return reject('rejected') }) } test().then(function() { //here when you resolve }) .catch(function(rej) { //here when you reject the promise console.log(rej); });

確保每次調用then()返回一個值。

例如

 var url = 'https://www.google.co.in'; var options = {}; var resolves = Promise.resolve(); resolves.then(() => { console.log('Resolved first promise'); var fetchPromise = fetch(url, options); fetchPromise.then(() => { console.log('Completed fetch'); }); }) .catch(error => { console.log('Error', error); });

請注意console顯示未捕獲的異常。 但是,如果您返回了內部承諾(或任何其他值,最終通過resolve變成了承諾),您最終會扁平化承諾,因此異常冒泡。

 var url = 'https://www.google.co.in'; var options = {}; var resolves = Promise.resolve(); resolves.then(() => { console.log('Resolved first promise'); var fetchPromise = fetch(url, options); return fetchPromise.then(() => { console.log('Completed fetch'); }); }) .catch(error => { console.log('Error', error); });

注意異常冒泡到外部承諾。 希望這可以使事情稍微澄清一些。

為什么不將它包裝在try / catch塊中,我已經從ivo 中復制了以下內容

function test() {
    return new Promise((resolve, reject) => {
        return reject('rejected');
    })};

(async ()=>{
    try{
        await test()
    }catch(er){
        console.log(er)
}})();

Promise 拒絕屬於then函數的第二個參數。

function test() {
    return new Promise((resolve, reject) => {
    return reject('rejected')
  })
}

test().then(function() {
  //here when you resolve
}, function(rej) {
  //here when you reject the promise
    console.log(rej)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM