如何获取useEffect hook中所有带Promise.all的数据?
How to get all the data with Promise.all in the useEffect hook?
我有这个 useEffect 钩子,它试图一次性获取所有数据
useEffect(() => {
let promises = [];
data.forEach(item => {
promises.push(fetch(`https://app.subsocial.network/subid/api/v1/check/${(item.name).toLowerCase()}`))
});
Promise.all(promises)
.then(response => response.map(item => item.json()))
.then(data => console.log(data))
.catch(error => console.log(error))
}, [data]);
但是,我在控制台中的数据是这样的:
json()
方法returns一个承诺。
这意味着您已经使用 Promise.all
等待所有响应承诺解决,但随后您只是生成了一堆新的 JSON 解析承诺。
在您使用 Promise.all
.
之前生成 JSON 解析承诺
即
promises.push(
fetch(`https://app.subsocial.network/subid/api/v1/check/${(item.name).toLowerCase()}`))
.then(response => response.json());
你快到了,你只需要分析你第一个得到的每一个承诺Promise.all
useEffect(() => {
let promises = [];
data.forEach((item) => {
promises.push(
fetch(
`https://app.subsocial.network/subid/api/v1/check/${item.name.toLowerCase()}`
)
);
});
Promise.all(promises)
.then((responses) => {
// Take all responses and analyze them with another Promise.all
return Promise.all(
responses.map((response) => {
return response.json();
})
);
})
.then((data) => {
// Extracted data
console.log(data);
})
.catch((error) => {
// Catched errors
console.log(error);
});
}, [data]);
在 then
方法中,您将获得所有响应,并用另一个 Promise.all
包装它们,以便您可以从中提取它们收到的内容。
我有这个 useEffect 钩子,它试图一次性获取所有数据
useEffect(() => {
let promises = [];
data.forEach(item => {
promises.push(fetch(`https://app.subsocial.network/subid/api/v1/check/${(item.name).toLowerCase()}`))
});
Promise.all(promises)
.then(response => response.map(item => item.json()))
.then(data => console.log(data))
.catch(error => console.log(error))
}, [data]);
但是,我在控制台中的数据是这样的:
json()
方法returns一个承诺。
这意味着您已经使用 Promise.all
等待所有响应承诺解决,但随后您只是生成了一堆新的 JSON 解析承诺。
在您使用 Promise.all
.
即
promises.push(
fetch(`https://app.subsocial.network/subid/api/v1/check/${(item.name).toLowerCase()}`))
.then(response => response.json());
你快到了,你只需要分析你第一个得到的每一个承诺Promise.all
useEffect(() => {
let promises = [];
data.forEach((item) => {
promises.push(
fetch(
`https://app.subsocial.network/subid/api/v1/check/${item.name.toLowerCase()}`
)
);
});
Promise.all(promises)
.then((responses) => {
// Take all responses and analyze them with another Promise.all
return Promise.all(
responses.map((response) => {
return response.json();
})
);
})
.then((data) => {
// Extracted data
console.log(data);
})
.catch((error) => {
// Catched errors
console.log(error);
});
}, [data]);
在 then
方法中,您将获得所有响应,并用另一个 Promise.all
包装它们,以便您可以从中提取它们收到的内容。