1

I have around five URL(api) i need to fetch. I have made an array with the urls. I need to make a for loop so i can get each url-info into different boxes. I started earlier with fetch url, then i wrote down +info.name+ etc on each thing i wanted to get out at the page, but it will take to long time, so i need to use a for loop. How do i do that? So i dont have to fetch and write +info+ so many times?

var urls = ["url i need to fetch",
"url i need to fetch",
"url i need to fetch",];

var url = "url i wanted to fetch";

fetch (url)
.then (result => result.json())
.then ((res) => {
console.log(res);
createCards (res);

})
.catch(err => console.log(err))

function createCards(card) {
var div = document.getElementById('card');



div.innerHTML = `


<h2>`+card.name+`</h2>
      <div>
      <b>HTML text </b>`+info.from.card+`</div>
2
  • Can you use async/await? Commented Nov 15, 2018 at 15:23
  • Have not used that before, so the best is if someone can help me with how Im gonna fetch it all with a for loop Commented Nov 15, 2018 at 15:24

2 Answers 2

1

You can use Promise.all() to run all requests at the same time:

const urls = [
  "url i need to fetch",
  "url i need to fetch",
  "url i need to fetch"
];
Promise
  .all( urls.map( url => fetch( url)))
  .then( responses => responses.map( response => response.json()))
  .then( results => {
    // do something with the results array
  })
  .catch( error => {
    // handle the error
  });
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a for loop and use let which creates a block level scope

var urls = ["url1", "url2", "url3"];

for (let i = 0; i < urls.length; i++) {
  fetch(urls[i])
    .then(result => result.json())
    .then((res) => {
      console.log(res);
      createCards(res);
    })
    .catch(err => console.log(err))
}

function createCards(card) {
  var div = document.getElementById('card');
  div.innerHTML += `<h2>${card.name}</h2>
                  <div>
                  <b>HTML text </b>${someOtherText}</div>`
}

1 Comment

Should mention that the order of output may not be same as order of url array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.