javascript - Promise catch,如何返回一个新的替代promise继续?

标签 javascript promise

我正在尝试 fetch() 一个文件,如果失败,我想尝试替代文件。
这个嵌套的 Promise() 感觉很脏。什么是更好的解决方案?

fetch('file1.csv')
    .then(function(response){
        if (response.status !== 200) {
            throw 'file1 no 200 response';
        }
        return response;
    })
    .catch(function(){
        return fetch('file2.csv')
                .then(function(response){
                    if (response.status !== 200) {
                        throw 'file2 no 200 response';
                    }
                    return response;
                })
    })
    .then(function(response){
        console.log('got file1 or file2, continue... then() ...');
        console.log(response);
    })
    .catch(function(err){
        console.log('both files not found');
    });

最佳答案

为了让它更干,你总是可以使用一个函数。

function getFile(name) {
  return fetch(name)
      .then(function (response) {
        if (response.status !== 200) {
          throw `${name} no 200 response`;
        }
        return response;
      });
}


getFile('file1.csv')
    .catch(function () {
      return getFile('file2.csv');
    })
    .then(function (response) {
      console.log('got file1 or file2, continue... then() ...');
      console.log(response);
    })
    .catch(function (err) {
      console.log('both files not found');
    });

关于javascript - Promise catch,如何返回一个新的替代promise继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54853182/

相关文章:

javascript - Promise.all 响应

javascript - YAML 文件中的换行符

javascript - "Javascript: The good parts"中的闭包示例

javascript - 未调用 jQuery Slide Toggle 函数

javascript - Angular foreach 等待 http 调用的问题

javascript - JavaScript 中的 promise /获取 : how to extract text from text file

Javascript 在 html 文件中不起作用

javascript - 检查参数是否传递给 Javascript 函数

javascript - 故事书构建每次都会失败

javascript - 如何通过 promise 映射