假设我们要获取三个文件。我们可以这样做:
fetch("./1.json")
.then((response) => {
return response.json();
})
.then((text_1) => {
fetch("./2.json")
.then((response) => {
return response.json();
})
.then((text_2) => {
fetch("./3.json")
.then((response) => {
return response.json();
})
.then((text_3) => {
console.log("Done")
});
});
});
但是这种嵌套会使代码过于复杂。是否有任何解决方法?
它们都可以同时或顺序获取
答案 0 :(得分:4)
一个简单的解决方案是像这样使用 Promises:
Promise.all([
fetch("./1.json").then((response) => response.json()),
fetch("./2.json").then((response) => response.json()),
fetch("./3.json").then((response) => response.json()),
]).then((values) => console.log(values));
它应该将响应记录为一个数组,例如:
["res1", "res2", "res3"]
答案 1 :(得分:1)
如果需要串联处理它们,您可以为每个创建单独的回调:
const handleResponse1 = (text_1) =>
fetch("./2.json").then(res => res.json()).then(handleResponse2);
const handleResponse2 = (text_2) =>
fetch("./3.json").then(res => res.json()).then(handleResponse3);
const handleResponse3 = (text_3) => console.log("Done");
fetch("./1.json").then(res => res.json()).then(handleResponse1);
如果您希望同时获得所有响应,您可以解构 Promise.all
结果。
const requests = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3'
];
const fetchJson = async (request) =>
fetch(request).then(response => response.json());
const fetchJsonAll = async (requests) =>
Promise.all(requests.map(fetchJson));
(async () => {
const [ res1, res2, res3 ] = await fetchJsonAll(requests)
.catch(err => console.log(err.message));
console.log(JSON.stringify(res1));
console.log(JSON.stringify(res2));
console.log(JSON.stringify(res3));
})();
.as-console-wrapper { top: 0; max-height: 100% !important; }
答案 2 :(得分:1)
const allPromises = [fetch("./1.json"), fetch("./2.json"), fetch("./3.json")]
Promise.all(allPromises).then((values) => {
console.log(values);
});
答案 3 :(得分:0)
您可以使用循环以及 async
/await
:
async function fetchStuff() {
const files = ["./1.json", "./2.json", "./3.json"];
for (let i = 0; i < files.length; i++) {
const result = (await fetch(files[i])).json();
}
console.log("Done");
}
fetchStuff();