Search code examples
node.jsservergoogle-apigoogle-calendar-apibackend

nodeJS async await with Google API


I'm using the Google Calendar API which works as expected. But I have a problem with the async methods inside there.

So I have following request route to get all events from my specific user:

router.get('/api/user/calendar/listEvents', async (req, res) => {
  try {

    const token = "123456789"

      var oAuth = authorizationHelper(token)

         var events = await listEvents(oAuth, req.body.date)

    res.status(200).send(events)
  } catch (e) {
    res.status(400).send("Error Bad Request")
    console.log(e)
  }
})

And my listEvents method :

   async function listEvents(auth, date) {
  var events;
  const calendar = google.calendar({ version: 'v3', auth });
   const eventsA = calendar.events.list({
    calendarId: 'primary',
    timeMin: date,
    maxResults: 1,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    events = res.data.items;
    return events
  });
}

The listEvents Method is working fine, but the return of this function is always undefined because it's not waiting for the response which I get back from the Calendar API.

Does anyone know a solution for this issue ?


Solution

  • You cannot return from an async function as you are returning in listEvents function, it will always return undefined;

    Solution: You could wrap the code in a promise and then pass the data in resolve method.

    Working Example:

    async function listEvents(auth, date) {
      var events;
      const calendar = google.calendar({ version: 'v3', auth });
      return new Promise((resolve, reject) => {
        const eventsA = calendar.events.list({
          calendarId: 'primary',
          timeMin: date,
          maxResults: 1,
          singleEvents: true,
          orderBy: 'startTime',
        }, (err, res) => {
          if (err) {
            console.log('The API returned an error: ' + err);
            reject('The API returned an error: ' + err);
            return;
          }
          events = res.data.items;
          resolve(events)
        });
      });
    }