Fetch from two API calls

Hi everyone,

I’m working on the FCC’s random quote machine project, and I’m using two APIs here, one for quotes and one from Unsplash to change the background image each time I reload the page or click to generate a new quote, and because the image takes a long time to load I thought I can try to fix this by waiting for the image first and then display the other quote. So I thought I’d try and call them (the APIs) together by using promise.all, I’ve tried this example found online but I didn’t know how to implant it knowing that the second API (from Unsplash) don’t send a JSON, it’s just a normal URL. So how do I fix this and is this the right fix for my issue (image don’t change instantly)

That’s the code I’m trying to use:

function renderHTML(quoteAPI, imageAPI) {
 // Rest of the code here
}

function getData() {
  let quoteAPICall = fetch("https://api.quotable.io/random");
  let imageAPICall = fetch("https://source.unsplash.com/1980x1280/?wallpaper");

  Promise.all([quoteAPICall, imageAPICall])
    .then(values => Promise.all(values.map(value => value.json())))
    .then(finalVals => {
      let quoteAPIResp = finalVals[0];
      let imageAPIResp = finalVals[1];
      renderHTML(quoteAPIResp, imageAPIResp);
    });
}```

And that's my current code 
[CodePen](https://codepen.io/faissalabsml-the-styleful/pen/vYKGpWZ)

Why you use Promsie.all in resolve

see the docs it’s pretty forward https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
and add the url of your code so i can see the result.

I would assume that it is the actual image download and loading onto the page that is slow and not the API call. The API just give you JSON with the resource links, but it is the resources that are slow to get and load, not the API call. What I’m saying is I don’t really think using Promise.all is the solution you are looking for.

For the image to finish loading onto the page before showing the quote, you would likely need to “observe” (event-driven or otherwise) the image load state. But there is one small issue, you are using a background-image in the CSS. So as far as I can tell you would need to look at the load event on an image element and then set the image in the CSS inside that load event and not show the quote until after the image is set (I think caching might make it so you do not fetch the image twice).

I’m sure there are libraries or example code for doing this (google search).

Yeah you’re right , I realized after many tires that Promise.all won’t fix it. So I guess the best solution is what you mentioned. Thank you so much

No problem. It would be cool if you gave us an update when you come up with a solution. Up to you, of course.

Happy coding!

1 Like

I’ll try to, thanks again