承诺捕获,如何回归新的替代承诺继续?

问题描述 投票:4回答:2

我正在尝试获取()一个文件,如果失败,我想尝试替代文件。 这个嵌套的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');
    });
javascript promise
2个回答
© www.soinside.com 2019 - 2024. All rights reserved.