-2

Currently, I have a list named appointments initialized outside of a function, and my code is pushing objects into this array from within that function.

var appointments = [];
async function getAllAppointmentEvents() {
    var doctorList = await getAllDoctors();
    // For all doctors
    for (let i = 1; i < doctorList["doctorinfo"].length; i++) {
        // Find their appointments
        schedule = await getAppointmentsByDoctor(i).then(function (response) { return response; });
        // For each appointment
        if (schedule["schedules"] !== undefined) {
            for (let j = 0; j < schedule["schedules"].length; j++) {
                var startDate = new Date(schedule["schedules"][j]["datetime"]);
                // startDate = new Intl.DateTimeFormat("")
                var endDate = new Date(schedule["schedules"][j]["datetime"]);
                endDate.setHours(startDate.getHours() + 1);
                var result = {
                    title: doctorList["doctorinfo"][i][1],
                    start: startDate.toISOString().slice(0, 19),
                    end: endDate.toISOString().slice(0, 19),
                    color: "#C0C0C0",
                    groupId: doctorList["doctorinfo"][i][0]
                };
                appointments.push(result);
            }
        }
    }
}

When I console.log the output, I get an empty array that seems to contain all all the objects. But i'm unable to access the objects by appointments[0]. I've also tried printing out Object.keys(appointments) and it doesn't have any keys either. When I console.log inside the function, the array is accessible as per normal.

The output I get when I console.log the list from outside of the function: output

I need help accessing the objects from outside of the function. Thanks!

tammi
  • 143
  • 2
  • 8

1 Answers1

-1

Your first for loop is a sychronous operation. At each operation it will run through the operations inside the loop block, and move onto the next iteration (i++, and repeat all).

Inside the synchronous loop, you have an asynchronous operation:

schedule = await getAppointmentsByDoctor(i).then(function (response) { return response; }); 

The sync loop doesn't work well with your async operation - probably why your array isn't filled up by the time you expect it to be.

You can use an implementation of Promise.all with the current async/await to solve your issue.

You can also look for an asyncForEach implementation, like in this article and in this gist.

Gist content in case it is removed:

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
const asyncForEach = async (array, callback) => {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array)
  }
}

const start = async () => {
  await asyncForEach([1, 2, 3], async (num) => {
    await waitFor(50)
    console.log(num)
  })
  console.log('Done')
}

start()
saglamcem
  • 677
  • 1
  • 8
  • 15
  • When giving an -1, if you explain why you did it, you'll be able to help me not repeat the same mistake. – saglamcem Mar 17 '20 at 08:15