0

I am making multiple api calls and I want to store the data received in an array, but when I log the array at the end, it returns empty value (or just what the array was initialized with). The data also isn't written to my file.

for(const org of orgs){
    axios.get(prod + getAllAppsInOrg + org)
        .then((res1) => {
            let collectedData = ["Org,Space,ServerName,AppName,Instances,Memory,DiskQuota"];

            for(const app of [res1.data[0]]){
            //res1.data.forEach( async (app, index) => {
                const formData = new URLSearchParams({
                    orgName: org,
                    space: app.spaceName.replace(" ", ""),
                    appName: app.appName
                });

                axios.post(prod + getAppInfo, formData)
                    .then((res2) => {
                        for(const dp of res2.data){
                        //res2.data.forEach( async (dp) => {
                            let datapoint = "";

                            datapoint += org + ",";
                            datapoint += dp.space + ",";
                            datapoint += dp.serverName + ",";
                            datapoint += app.appName + ",";
                            datapoint += dp.instances + ",";
                            datapoint += dp.memory + ",";
                            datapoint += dp.disk_quota;

                            collectedData.push("\n", datapoint);
                        }
                    })
            }

            console.log(collectedData);

            //fs.writeFileSync(__dirname + "/data/" + org + "_prod.csv", collectedData.toString());
        })
}
trs123
  • 1
  • 2
  • forEach with async can't work. Use a for..of loop (serial) or Promise.all with .map (parallel) instead. – CherryDT Apr 21 '22 at 14:48
  • `Promise.all` expects you to pass it an array of promises. You're passing it an empty array (and then, after it has run, the async function you are calling in a loop populates that array with strings). – Quentin Apr 21 '22 at 14:48
  • @CherryDT I replaced the foreach loops with for of loops and im getting the same result – trs123 Apr 21 '22 at 15:06
  • Edit the question accordingly, please. – CherryDT Apr 21 '22 at 15:08
  • @CherryDT Done! Sorry! – trs123 Apr 21 '22 at 15:37
  • You are not `await`ing your requests. (also the use of `then` is unnecessary, it should just use the return value of the awaited call.) – CherryDT Apr 21 '22 at 15:52

0 Answers0