首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Fetch API发送多个请求,并等待它们完成后再执行另一段代码

使用Fetch API发送多个请求,并等待它们完成后再执行另一段代码
EN

Stack Overflow用户
提问于 2022-09-17 11:03:21
回答 1查看 72关注 0票数 1

我有太多的fetch api请求和一些代码。我希望Fetch API异步发送请求,但在执行下一段代码之前等待它们的结果。

代码示例:

代码语言:javascript
运行
复制
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });

//some code to run after above requests processing.

相同的多个获取请求。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-17 11:10:27

您可以使用Promise.all()

代码语言:javascript
运行
复制
Promise.all([
  fetch(url, {method: 'post', body: someData}), // first fetch
  fetch(url, {method: 'post', body: someData}), // second fetch
  ...
]).then((data) => {
  const [firstFetchResult, secondFetchResult, ...] = data;
  // data processing
}).then(() => {
  // some code to run after above requests processing.
})

如果您对每个提取结果都有一些自定义逻辑--您可以为自定义函数使用一些映射。在本例中,映射基于map()索引(回调的第二个参数):

代码语言:javascript
运行
复制
// Some functions map - first custom functions for first fetch ect;
const FM_MAP = [
  (data) => data.substring(40, 50).replace('a', 'b'),
  (data) => data.substring(1, 10),
  (data) => [...data.substring(25, 30)].join('-_-')
]

Promise.all([
  fetch('google.com'),
  fetch('google.com'),
  fetch('google.com')
]).then((responses) => Promise.all(
  // you can work with responses just like with regular arrays
  responses
    .map((response, index) => response.text().then((data) => {
      // custom functions for every data result
      console.log(FM_MAP[index](data))
    }))
))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73754309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档