skip to Main Content

I have an axios function, which I want to call several times, then I want to firstly sort received data and then store it. But now all my promises results are undefined.

const arr = {...checkbox};
const keys = Object.keys(arr).filter((k)=>{
   return arr[k] == true;
});

let promises = [];
for (let i=0;i<keys.length;i++) {
   promises.push(
     axios.get(`my/api/${keys[i]}`).then(
       function(response){
             response.data.sort()
       }
     ).catch((err) => error.value = err)
   )
}
Promise.all(promises).then(() => console.log(promises));

2

Answers


  1. The issue with your code is that you are not returning the sorted data from the Axios promise. You are sorting the data within the promise but not returning it.

    
    const arr = {...checkbox};
    const keys = Object.keys(arr).filter((k)=>{
       return arr[k] == true;
    });
    
    let promises = [];
    for (let i=0;i<keys.length;i++) {
       promises.push(
         axios.get(`my/api/${keys[i]}`).then(
           function(response){
             return response.data.sort()
           }
         ).catch((err) => error.value = err)
       )
    }
    Promise.all(promises).then((sortedDataArray) => {
      const sortedData = [].concat(...sortedDataArray);
      sortedData.sort(); 
      console.log(sortedData); 
    }).catch((err) => error.value = err);
    
    
    

    In this code above the axios promise returns the sorted data using the return statement, and the Promise.all() method waits for all promises to resolve and returns an array of sorted data

    Login or Signup to reply.
  2. You are not returning the data from your then clause. Try this:

    for (let i=0;i<keys.length;i++) {
       promises.push(
         axios.get(`my/api/${keys[i]}`).then(
           function(response){
                 return response.data.sort()
           }
         ).catch((err) => error.value = err)
       )
    }
    

    and then show it like this

    Promise.all(promises).then((res) => console.log(res));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search