0

I have this code, wherein i'd like to make it in single array.

The output that data produce, is like this:

console.log(await data)

  connections.elements.map((val: any) => {
   const url = 'link'
   return new Promise((resolve) => {
      axios.post(url, val.firstName).then((res: { data: any }) => {
        resolve(searchRequestBuilder(res.data.AllResults));
      });
    });
  });

  const searchRequestBuilder = async (data: any) => {
    console.log(await data);
    // for await (let resolvedPromise of data) {
    // console.log(resolvedPromise);
    // }
  };

What I'd like to do is like this: Single Array

I already tried to make a variable and use .push, but it still doesn't combine in a single array. What was the thing I am missing?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user16691768
  • 93
  • 1
  • 8
  • 1
    What is the value of `res.data.AllResults`? Why are you `await`ing it in `searchRequestBuilder`? – Felix Kling Aug 31 '21 at 18:17
  • Check `.flat()` : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat – Samuli Hakoniemi Aug 31 '21 at 18:17
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it), and don't use `for await`. – Bergi Aug 31 '21 at 18:55
  • Sounds like you're looking for `const responses = await Promise.all(connections.elements.map(val => axios.post(url, val.firstName))); const data = responses.flatMap(res => res.data.AllResults); for (const item of data) console.log(item);` – Bergi Aug 31 '21 at 18:57

3 Answers3

0

You can try using .concat:

let allData = [];
allData = allData.concat(await data);
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

The main problem there could be you are making a new call per each item of your elements array. This may create performance issues. The best practice may be to do only one async call and then get all items.

Anyway, if for some reason you really need to make all these ajax calls. Think you are working with asynchronous code, then you really don't know when all calls are answered. To fix this, you need to call your searchRequestBuilder after had made all calls.

I suggest you use Promise.all method. I left you this link to show you how it works. Basically what you need to do is save all axios.post promises in an array and after loop your elements array call Promises.all passing the array with your promises, then you will be able to execute your searchRequestBuilder without problems.

jircdeveloper
  • 424
  • 2
  • 17
0

So since your .map function will return an array of promises, you can store that in a variable, and you can use Promise.all or Promise.allSettled to wait for all the apis to resolve and you can get all the results in a single array in the order that it is requested.

Not part of the question, another thing is if you are not careful, and use await on each api request, it can make a waterfall pattern of requests, which means it will wait for API 1 to finish, then API 2 to finish. But the way its written here, it will make all the requests parallely, so this will request all the APIs together, and once the last one gets resolved the Promise.all or allSettled will trigger its callback.

    const searchRequestBuilder = async (data: any) => {
         console.log(await data);
    }
    async function makeAPIrequests(){    
         let arrrayOfPromises = connections.elements.map((val: any) => {
           const url = 'link'
           return new Promise((resolve) => {
              axios.post(url, val.firstName).then((res: { data: any }) => {
                resolve(searchRequestBuilder(res.data.AllResults));
              });
            });
          });
        
         Promise.allSettled(arrrayOfPromises).
            then((results) => console.log(results))
 
    }

Edit: Also in addition to this, I do not think that you need to return a new Promise inside the map funciton, if you just return axios it should work, since axios itself will return a promise.

albseb
  • 169
  • 5
  • this is what I need. Thank you very much. what I did is directly have `resolve(res.data.AllResults);` then `Promise.allSettled(arrrayOfPromises).then((results) => console.log(results));` – user16691768 Aug 31 '21 at 19:56