1

Able to log the data(array of objects) to the console without iterating. I understand the data that I am fetching in a for loop might not have finished executing all the get requests by the time I am using allOrders later but I am just not able to find a solution for this. Thanks for your help.

   
const pageCount = Math.ceil((sortBy === 'deliveryInfo.slotStart' ? countTotalDeliveryDatePageResp : pageResponse) / 20);

// for excel export
let allOrders = [];

let promises = [];

      for(let pageNum = 0; pageNum < pageCount; pageNum++){

        let excelOrderAPI = sortBy === 'deliveryInfo.slotStart' ? "orders/delivery/"+region_id+"/"+endDeliveryDate+"?page="+pageNum+"&size=20" : "/orders/details/?page="+pageNum+"&placedDate.specified=true&placedDate.greaterThanOrEqual="+startDate+"&placedDate.lessThanOrEqual="+endDate+"&size=20&sort="+sortBy+",desc&status.in="+selected.join(',')+"";
        
        promises.push(

          axios.get(excelOrderAPI, {
                    headers: {
                    'Authorization': jwtToken,
                    'Accept' : '*/*',
                    'Content-Type': 'application/json',
                    'App-Token' : 'A14BC'
                      }
            })
            .then(order =>{
  
              if(order.data != null && order.data.length > 0){
                    order.data.map(res=>{
                          allOrders.push(res)
                      })
                
                }
 
           })

        )//end of push()
        

      }


   Promise.all(promises);

MrStack
  • 27
  • 6
  • What does the order structure look like? What errors are you getting? in your `.then`, you should definitely have the full response available to you - the point of the promise resolving is that the data is complete. – cmbuckley Aug 25 '21 at 16:32
  • Hi @cmbuckley, the data is an array of objects. Am not getting any error but only blank output. even window.alert() shows nothing. I do get the data and I am able to log to the console after Promise.all(promises); statement. But I am not able to use the data to iterate through it. – MrStack Aug 25 '21 at 16:50

1 Answers1

1

Try with this async/await style code. I find it much more readable than promise chaining.

const mainFunction = async () => {
   // for excel export
   let allOrders = [];
   const pageNum = 0;
   while (pageNum < pageCount) {
     let excelOrderAPI =
       sortBy === "deliveryInfo.slotStart"
         ? "orders/delivery/" +
           region_id +
           "/" +
           endDeliveryDate +
           "?page=" +
           pageNum +
           "&size=20"
         : "/orders/details/?page=" +
           pageNum +
           "&placedDate.specified=true&placedDate.greaterThanOrEqual=" +
           startDate +
           "&placedDate.lessThanOrEqual=" +
           endDate +
           "&size=20&sort=" +
           sortBy +
           ",desc&status.in=" +
           selected.join(",") +
           "";
 
     const order = await axios.get(excelOrderAPI, {
       headers: {
         Authorization: jwtToken,
         Accept: "*/*",
         "Content-Type": "application/json",
         "App-Token": "A14BC",
       },
     });
 
     if (order.data != null && order.data.length > 0) {
       order.data.map((res) => {
         allOrders.push(res);
       });
     }
     pageNum++;
   }

    return allOrders;
 };

const allOrdersData = mainFunction(); allOrdersData.then(function(result){ 
                result && result.map(res=>{// do something 
                with the result}); 
             });
MrStack
  • 27
  • 6
omeanwell
  • 1,847
  • 1
  • 10
  • 16
  • Sure @omeanwell. Thank you for the code. I will try it out and will mark your code as the solution if it works out. – MrStack Aug 25 '21 at 17:08
  • Sounds good! Let me know if there are any issues – omeanwell Aug 25 '21 at 17:20
  • Your solution is perfect @omeanwell. Thank you again!! Just like to suggest you one thing. Can you add this line of code to yours: **const allOrdersData = mainFunction(); allOrdersData.then(function(result){ result && result.map(res=>{// do something with the result}); });** . Actually I got this on the console: **Promise { }** . So had to google search ([link] (https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val)). It could be useful to somebody in the future. – MrStack Aug 25 '21 at 18:22