簡體   English   中英

Promise.all 中的提取失敗,未捕獲錯誤

[英]Failing fetch in a Promise.all not catching error

我有多個 JSON 需要加載,並且必須檢查它們是否都被很好地獲取。 所以我使用 Promise.all 來等待所有的fetch

第一個valid.json存在,而不是第二個,所以第二個fetch以 404 結束。但是盡管有Promise.rejectPromise.all仍然記錄Success! 而不是拋出最后一個錯誤。

我是否遺漏了Promise.all工作原理?

const json_pathes = [
    'valid.json',
    'not_valid.json'
];

function check_errors(response) {
    if (!response.ok) {
        Promise.reject('Error while fetching data');
        throw Error(response.statusText + ' (' + response.url + ')');
    }
    return response;
}

Promise.all(json_pathes.map(url =>
    fetch(url)
        .then(check_errors)
        .then(response => response.json())
        .catch(error => console.log(error))
))
.then(data => {
    console.log('Success!', data);
})
.catch(reason => {
    throw Error(reason);
});

// Console:
// Error: "Not Found (not_valid.json)"
// uncaught exception: Error while fetching data
// Array [ […], undefined ]

(當然檢查了所有類似的問題,但沒有任何幫助😕)


編輯 - 以下答案后的固定代碼:

const json_pathes = […]
Promise.all(json_pathes.map(url =>
    fetch(url)
        .then(response => {
            if (!response.ok)
                throw Error(response.statusText + ' (' + response.url + ')');
            return response;
        })
        .then(response => response.json())
        .catch(error => {
            throw error;
        })
))
.then(data => {
    // Success
})
.catch(error => {
    throw error;
});

這個電話:

 .catch(error => console.log(error))

...將返回一個已履行的承諾,而不是一個被拒絕的承諾。 每當您對待拒絕並希望將其冒泡為拒絕時,您應該明確地這樣做:

 .catch(error => {
       console.log(error);
       throw error; // cascade...
 })

順便說一句,這根本沒有影響

 Promise.reject('Error while fetching data');

...因為你沒有對這個新創建的、被拒絕的承諾做任何事情。

使用 .catch() 方法時必須再次拋出錯誤,否則錯誤將被靜音

Promise.all(
  json_paths.map(url => 
    fetch(url)
      .then(response => response.json())
      .catch(err => {
        console.log(err);
        throw err
      })
  )
).then(data => {
  // all promise resolved
  console.log(data)
}).catch(err => {
  // some promise may not be resolved
  console.log(err)
})

暫無
暫無

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

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