0

I'm trying to connect to Google Calendar's API. In fact, I am able to get correctly the JSON back. However, I'm not capable of extracting that JSON to use it later in the code. What happens is that the code continues executing although the user hasn't logged-in, which lead into a undefined variable and I can't return the variable with the JSON info.

Here is the code I have used. It is based on the Google's example code.

//Here There are the declared variables


/**
 *  Sign in the user upon button click.
 */
function handleAuthClick() {
    tokenClient.callback = async (resp) => {
        if (resp.error !== undefined) {
            throw (resp);
        }
        eventsJson = await listUpcomingEvents();
    };
    

    console.log(eventsJson); //  <----

    if (gapi.client.getToken() === null) {
        // Prompt the user to select a Google Account and ask for consent to share their data
        // when establishing a new session.
        tokenClient.requestAccessToken({prompt: 'consent'});
    } else {
        // Skip display of account chooser and consent dialog for an existing session.
        tokenClient.requestAccessToken({prompt: ''});
    }

    
    return eventsJson;
}

/**
 * Print the summary and start datetime/date of the next ten events in
 * the authorized user's calendar. If no events are found an
 * appropriate message is printed.
 */
async function listUpcomingEvents() {
    let response;
    try {
        const request = {
        'calendarId': 'x',
        'timeMin': (new Date()).toISOString(),
        'showDeleted': false,
        'singleEvents': true,
        'maxResults': 10,
        'orderBy': 'startTime',
        };
        response = await gapi.client.calendar.events.list(request);
    } catch (err) {
        return;
    }

    var events = response.result.items;
        if (!events || events.length == 0) {
            console.log("No events Found");
            return;
    }
    // Flatten to string to display
    console.log(events);
    const output = events.reduce(
        (str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
        'Events:\n');
    console.log(output);
    
    return events;
};


document.getElementById('authoriseButton').addEventListener('click', async () => {
    eventss = await handleAuthClick();

    console.log('Events: ' + eventss); //  <----
});

document.getElementById('logOutButton').addEventListener('click', () => {
    handleSignoutClick();
});

Both console.log() I have pointed are used to control. My problem is that, when I click authoriseButton, both console.log() are executed and they print the value of undefined. Later, when I finish doing the log-in in google all the information is obtained correctly.

My question here is the next one: how can i stop the execution of the code until the variable eventss or eventsJson is not undefined.

I have tried multiple ways of using async/await but I cannot solve the problem.

NOTE: I don't use any webpack or similars, all is executed in the browser.

Thanks by advance for helping me.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51

0 Answers0