0

I have been looking at Promise.all for fetching multiple urls. I know that we can use Promise.all and pass an array there, and then fetch the content.

Let's say I have two URLs in an array but one of them is not working. How can I still use Promise.all? What is the other method fetching both? I would fetch both but if one of them is not working don't fetch the one that is not working.

const urls = [ instagramURL, facebookURL];

const thepromises = urls.map((url) => fetch(url)
  .then((resp) => resp.json()));
  Promise.all(thepromises).then((post) => {
  console.log(post);
});
Andy
  • 61,948
  • 13
  • 68
  • 95

2 Answers2

0

Wrapping your function with try...catch statments will help you testing a block of code for errors while the code being excuted.

for example, you can try this :

const urls = [ instagramURL, facebookURL];

try {
      let promiseArray = [];
      for (let i = 0; i < urls.length; i++) {
        promiseArray.push(fetch(urls[i]));
      }
     const results = Promise.all(promiseArray);
     console.log(results);
    } catch (err) {
      console.log(err);
    }
Omar Dieh
  • 500
  • 3
  • 8
  • You should a description/commentary on why you think this is a good answer that will solve the problem. – Andy Jul 09 '22 at 14:07
  • hey @Andy thanks for your comment, I have just updated my answer with your suggestions :) – Omar Dieh Jul 09 '22 at 14:15
  • Note that `fetch` also has a `catch` method so you may not need `try/catch`. – Andy Jul 09 '22 at 14:16
  • @OmarDieh and Andy thank for your answer. i used bioth sugestion in some way. so i tried to make an url to give an error like on the code im goint to post right now . let promiseArray = []; for (let i = 0; i < urls.length; i++) { promiseArray.push(fetch(urls[i])); } const results = Promise.all(promiseArray); results.then((items)=>{ for(let item of items){ if(item.status === 200){ console.log(item) } } }).catch(error => console.log(error)) – Vinicius Chinen Jul 09 '22 at 15:25
  • im being able to get the one with no error. however on my console it showing another error on promiseArray.push(fetch(urls[i])); line. it is showing GET https://graph.facebook.com/ ...... 400 . i dont want to get the url with 400 status . how can i remove this error? – Vinicius Chinen Jul 09 '22 at 15:29
0

use promise.allSettled[instagramURL, facebookURL]

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 03 '23 at 07:51