如何执行多个提取请求
我想对React/JavaScript进行多个提取请求,我尝试了以下尝试哪种作品:
const fetchAll = async () => {
Promise.all([
await fetch('/api/...'),
await fetch('/api/...')
]).then(links => {
const response1 = links[0];
const response2 = links[1];
timeData = response1.json();
functionData = response2.json();
})
}
但是我想这样做,因为这似乎更有用。如果可能的话,我想在USESTATE中使用使用效率和使用情况并加载不同阵列中不同API的数据。这是一个示例:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/api/..")
.then((response) => response.json())
.then((r) => {
setData(r);
});
}, []);
有没有办法来为多个请求执行此操作并将数据保存在不同的数组中,以便以后可以访问它们?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我正确理解您的问题,那么我认为您想要这样的东西:
在这里,我们利用
useffect
使您的同时fetch
es eS;我们真的不需要也不需要使用等待
,因为我们希望它们同时运行,并且Promise.All
才能在数组中的所有承诺解决时才能解决。在。您的组件。您可能想确保您有一个 useffect
,以确保仅在您想要的条件下执行它。这将适用于一些有限数量的获取 - 对于动态的东西或大量的提取物,这种方法可能不太理想,并且您想要的东西可以更好。If I'm understanding your question correctly, then I think you want something like this:
Here we leverage a
useEffect
to make your simultaneousfetch
es; we don't really need nor want to useawait
because we want them to run simultaneously and thePromise.all
will only resolve when all the promises in the array resolve. In the.then
of thePromse.all
, you can parse out the responses just as you did in your original example and set them in state hooks you've defined earlier in your component. You'd probably want to make sure that you have an appropriately-defined dependency array passed as a second arg to youruseEffect
, in order to make sure that it only executes under the conditions in which you want it to. This would work for some limited number of fetches-- for something dynamic or with very large numbers of fetches, this approach would probably be less ideal, and you'd want something that scaled better.可以通过
,在某些模块
和组件中创建一些辅助功能...
This can be done nicely by
For example, create some helper functions in some module
and in your component...
尝试此尝试,
截至今天,现在在所有最新版本的主要浏览器中实现了Fetch,除了
IE11
外,包装器仍然可以有用,除非您对其使用多填充。然后,利用新的且现在更稳定的JavaScript功能,例如
破坏
andasync/等待
,您可能能够对同一问题使用类似的解决方案(请参阅代码以下)。我相信,即使一见钟情似乎似乎有些代码,但实际上是一种更清洁的方法。希望它有帮助。
Try this,
As of today, fetch is now implemented in all the latest version of the major browsers, with the exception of
IE11
, a wrapper could still be useful unless you use a polyfill for it.Then, taking advantage of newer and now more stable javascript features like
destructuring
andasync/await
, you might be able to use a similar solution to the same problem (see the code below).I believe that even though at first sight may seem a little more code, is actually a cleaner approach. Hope it helps.