JS 双重获取条件
JS Double Fetch condition
我正在从本地文件获取列表。但文件夹有时会发生变化。所以来这里问问你们是否正确,因为我认为有更好的方法来做,idk。请帮助我:)
fetch("./myJson.json")
.then(res => {
if(res.status != 404)
res.json()
else
fetch("../myJson.json")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
})
.then(data => console.log(data))
.catch(err => console.error(err));
谢谢!
您需要 return
回调中的嵌套承诺并使用 promise chaining feature:
fetch("./myJson.json").then(res => {
if (res.ok)
return res.json()
else
return fetch("../myJson.json").then(res => res.json());
}).then(console.log, console.error);
我正在从本地文件获取列表。但文件夹有时会发生变化。所以来这里问问你们是否正确,因为我认为有更好的方法来做,idk。请帮助我:)
fetch("./myJson.json")
.then(res => {
if(res.status != 404)
res.json()
else
fetch("../myJson.json")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
})
.then(data => console.log(data))
.catch(err => console.error(err));
谢谢!
您需要 return
回调中的嵌套承诺并使用 promise chaining feature:
fetch("./myJson.json").then(res => {
if (res.ok)
return res.json()
else
return fetch("../myJson.json").then(res => res.json());
}).then(console.log, console.error);