lurch101
lurch101

Reputation: 25

Using async to handle promise from Google Calendar API

I'm struggling with handling a call to the Google Calendar API. I've slightly modified the Node.js quickstart from the Google API docs for my needs. I'm trying to retrieve all events from the calendar but when I try to await the return, all I get is Promise { <pending> }. Is there a better way to wait for the call or is there something I'm totally missing?

async function listEvents() {
  const calendar = google.calendar({version: 'v3', auth: apiKey});
  return await calendar.events.list({
    calendarId: <calendarID>,
    timeMin: oneWeekAgo,
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = res.data.items;
    if (events.length) {
      events.forEach(el => console.log(el.summary))
      // console.log(events)
      // eventList = events
      return events
    } else {
      console.log('No upcoming events found.');
    }
  });
}

FWIW, the events do eventually log to the console, I just can't figure out how to get the function to wait for that promise to resolve before returning.

Upvotes: 0

Views: 2939

Answers (2)

vasu014
vasu014

Reputation: 207

This is the TypeScript code that I use to fetch calendar events

let results: GaxiosResponse<calendar_v3.Schema$Events>;
const maxResults: any = process.env.MAX_CALENDAR_RESULTS;
try {
    this.logger.info('Fetching events for primary calendar id');

    results = await gcalClient.events.list({
        calendarId: 'primary',
        timeMin: (new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()),
        maxResults,
        singleEvents: true,
        orderBy: 'startTime'
     });
     this.logger.info('Successfully fetched calendar events');
} catch (err) {
    this.logger.error('Error encountered while fetching events');
    this.logger.error(err);
    return err;
}
// Extract the Calendar Events from the response received
const eventList: calendar_v3.Schema$Event[] = results.data.items;

You can add this in an async function and return eventList, which will make the return type of the function to be Promise<calendar_v3.Schema$Event[]>

Now, wherever you call the function, use await or .then() to get the calendar events

Upvotes: 1

Ashish Modi
Ashish Modi

Reputation: 7770

You are trying to use await with a callback style. I guess if you just remove the callback function and put await it will return you the details

async function listEvents() {
  const calendar = google.calendar({version: 'v3', auth: apiKey});
  const res = await calendar.events.list({
    calendarId: <calendarID>,
    timeMin: oneWeekAgo,
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  });
  const events = res.data.items;
    if (events.length) {
      events.forEach(el => console.log(el.summary))
      // console.log(events)
      // eventList = events
      return events
    } else {
      console.log('No upcoming events found.');
    }
}

Upvotes: 0

Related Questions