1

I am a newbie to Javascript and I am in the middle of solving the last part of my program. However, I am experiencing difficulties with async await function as I am trying to get and store data from multiple requests and push it into an array which I want to use outside in the function. Later I want to render the content of this array(the quotes) and render it to the browser. Inside in my inner loop, I am able to console log my array but when I am trying to return it or use the function itself I ran into a problem. Any ideas?

I have an array of URLs which I am using to do multiple calls with because I need a certain amount of items in my array and the API provided doesn't get me more than 25 quotes per response.



const getQuotes = () => {
  let completeQuotesArray = [];
  const quotesPromises = urls.map(async url => {
    const response = await axios.get(url);
    console.log(response);
    return response.data.quotes;
  });
  for (const quotesPromise of quotesPromises) {
    let quotesArray = await quotesPromise;
    for (let i = 0; i < quotesArray.length; i++) {
      let quote = quotesArray[i].body;

      if (quote.length < 150) {
        completeQuotesArray.push(quote);
      }
    } 
  }
  return completeQuotesArray;
}
Clara
  • 51
  • 2
  • 3
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Randy Casburn Jun 09 '19 at 21:48
  • I'm not running your code, so I'm not 100% confident in my answer, but I think I see an error: The array of quotesPromises, is actually *not* an array of promises. You are awaiting for each axios request to resolve, and are storing the actual data in the array. So then, when you later await that data again in your for/of loop, it does not make sense, because the data is already there. Also, can you use Promise.all, instead of async-await? – RiverOceanSea Jun 09 '19 at 22:43
  • Thank you, Maiya, for your response. I haven't used Promise.all and I am not really sure how the code should be structured. What can I change in my current code so I can make it work? I assume you are talking about the line where I declare quotesArray = await quotesPromise. Is that correct? – Clara Jun 09 '19 at 22:57

1 Answers1

0

Here is a sample using the Promise.all mentioned to request your urls in parallel:https://jsfiddle.net/3w1yo9ts/

const quotesPromises = await Promise.all(urls.map(url => axios.get(url)))

Some additional comments are in the code for explanation and logs out the response so you can see what Promise.all does :) The response data is slightly different than yours, but I'm sure can be adjusted to your needs. I'd also recommend checking out try...catch to make sure a promise rejection is handled.

marsheth
  • 544
  • 3
  • 9