我正在尝试 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/