在循环JS内进行访存 [英] Fetch in fetch inside a loop JS

查看:39
本文介绍了在循环JS内进行访存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是,如何摆脱调用第二次提取300次的麻烦?还是有另一种方法可以做到,我正在做什么?另外,由于第一个api是来自api的异步异步方式,因此如何进行有序的(不想排序)调用?

The question is, how can I get rid of calling second fetch 300 times? Or is there another way to do that, what I`m doing? Additionally how to do ordered(don`t wanna sort) calls of first api, because they`re coming from api in chaotic asynchronous way?

for(let i=1;i<=300; i++) {
  fetch(`example.api/incomes/${i}`)   // should be returned 300 times
    .then(response => {
      if(response.ok) return response.json();
      throw new Error(response.statusText);
    })
    .then(function handleData(data) {
        return fetch('example.api')   // should be returned 1 time
        .then(response => {
            if(response.ok) return response.json();
            throw new Error(response.statusText);
          })
    })
    .catch(function handleError(error) {
        console.log("Error" +error);            
    }); 
};

推荐答案

您可以使用Promise all来解决它.

You can solve it using Promise all.

let promises = [];
for (let i = 1; i <= 300; i++) {
  promises.push(fetch(`example.api/incomes/${i}`));
}
Promise.all(promises)
  .then(function handleData(data) {
    return fetch("example.api") // should be returned 1 time
      .then(response => {
        if (response.ok) return response.json();
        throw new Error(response.statusText);
      });
  })
  .catch(function handleError(error) {
    console.log("Error" + error);
  });

这篇关于在循环JS内进行访存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆