0

I need to make two calls to two rest api, in the first with one of the data obtained, pass it to the second url and ai obtain what I want, I could achieve it with the code below but my boss tells me that it is wrong, first it I did with asyn await and it told me not to use it, then later with fetch and axios but it is not well written, what would be the correct way to do it with both axios and fetch cases? with axios

axios.all([axios.get(`${urlRestApi}`)]).then( 
      axios.spread(response1 => {                  
        let arrPost = response1.data.map(res => {
          return {
            titulo: res.title.rendered,
            contenido: res.content.rendered,
            extracto: res.excerpt.rendered,
            idImagen: res.featured_media,
          };
        });
        console.log("AQUI", arrPost);
         arrImg = arrPost.map(image => {
          axios.get(`${urlImage}/${image.idImagen}`)
          .then(urls => {   // urls returns 10 objects each with a corresponding image
            arrUrl.push(urls.data);  //for this reason I put all 10 in an array, but it happens 10 times
            if (arrUrl.length === 10) { // that's why when .length is 10 I go through it and assign what I want
              let arrImage = arrUrl.map(img => {
                return {
                  imagenes: img.source_url,
                };
              });
              console.log("TEST", arrImage);
              mostrarHTML(arrImage, arrPost); //I already have everything I run my function to print the data obtained
            }
          });
        });
      })
    );

and with fetch

 fetch(`${urlRestApi}`)
      .then(respuesta => {
        return respuesta.json();
      })
      .then(data => {
        let arrPost = data.map(data => { 
          return {
            titulo: data.title.rendered,
            contenido: data.content.rendered,
            extracto: data.excerpt.rendered,
            idImagen: data.featured_media,
          };
        });
        console.log(arrPost);
        arrImg = arrPost.map(image => {
          fetch(`${urlImage}/${image.idImagen}`)
            .then(res => {
              return res.json();
            })
            .then(urls => { // // urls returns 10 objects each with a corresponding image
              arrUrl.push(urls); //for this reason I put all 10 in an array, but it happens 10 times
              if (arrUrl.length === 10) { // that's why when .length is 10 I go through it and assign what I want
                arrImage = arrUrl.map(image => {
                  return {
                    imagenes: image.source_url,
                  };
                });
                console.log("aqui", arrImage);
                mostrarHTML(arrImage, arrPost); //I already have everything I run my function to print the data obtained
              }
            });
        });
      })
      .catch(error => {
        console.log(error);
      });
  • 1
    Didn't you ask your boss what's the right way then? You have not added what errors you are getting - it seems like a code standard problem, and the standard of code your company may want may not be what I feel is right. – Deepak Kamat May 18 '21 at 14:01
  • 1
    Also, I'd ask your boss why using `async`/`await` is not OK. – AKX May 18 '21 at 14:02
  • Well, there are always the good old [`XMLHttpRequest`s](https://stackoverflow.com/a/4033310/3776927). But TBH without a REALLY good reason for using them, I'd always prefer `fetch` – derpirscher May 18 '21 at 14:08

1 Answers1

0

With fetch, without async/await:

fetch(urlRestApi)
  .then((respuesta) => respuesta.json())
  .then((data) => {
    const posts = data.map((data) => ({
      titulo: data.title.rendered,
      contenido: data.content.rendered,
      extracto: data.excerpt.rendered,
      idImagen: data.featured_media,
    }));
    // Create an array of promises that fetch image data and combines it
    // with the original post.
    const imagePostPromises = posts.map((post) => {
      return fetch(`${urlImage}/${image.idImagen}`)
        .then((res) => res.json())
        .then((imageData) => ({
          // Combine the original post with the image data fetched
          ...post,
          imageData,
        }));
    });
    // Return a promise that resolves only when all of the `imagePostPromises` have finished.
    return Promise.all(imagePostPromises);
  })
  .then((postsWithImages) => {
    console.log(postsWithImages);
  });

And, much more readably, if only you could use async/await,

async function doThings() {
  const respuesta = await fetch(urlRestApi);
  const data = await respuesta.json();
  const posts = data.map((data) => ({
    titulo: data.title.rendered,
    contenido: data.content.rendered,
    extracto: data.excerpt.rendered,
    idImagen: data.featured_media,
  }));
  const imagePostPromises = posts.map(async (post) => {
    const res = await fetch(`${urlImage}/${image.idImagen}`);
    const imageData = await res.json();
    // Combine the original post with the image data fetched
    return ({
      ...post,
      imageData,
    });
  });
  const postsWithImages = await Promise.all(imagePostPromises);
  console.log(postsWithImages);
}
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thank you very much, I had the intuition that it was with Promises.all but it did not matter that if I did not use it now I see how to use it, thanks you have gotten me out of a mess – Francisco Sanvicente Pico May 18 '21 at 14:34