1

I have this function in an external file js:

export function getCalendarEvents() {
        gapi.client.load('calendar', 'v3', ()=> {       // load the calendar api (version 3)
          var request = gapi.client.calendar.events.list({
            'calendarId': 'primary',  // calendar ID
            'maxResults': 20,                 // show max of 20 events
            'singleEvents': true,               // split recurring events into individual events
            'timeMin':    (new Date()).toISOString(),           
            'orderBy':    'startTime'             // order events by their start time
          });

          // handle the response from our api call
          request.execute((resp) => {
            for (var i = 0; i < resp.items.length; i++) {   // loop through events and write them out to a list

              console.log(resp.items[i].summary + ' ' +resp.items[i].start.dateTime);
            };

          });
        });
      }

and i need to use "resp.items" value in my enter js file:

    import {getCalendarEvents} from './GoogleCalendarEvents';
componentWillMount(){
        var myitems = getCalendarEvents(); //my resp.items
    }

How can i do that? I know there are a lot of response but i want to understand the asynchronous pattern on my example.

2

1 Answer 1

2

Rewrite your function in file like this:

    export function getCalendarEvents( callback ) {
      ...

      // handle the response from our api call
      request.execute((resp) => {
        ...
        callback( resp )
      };

    });

    import {getCalendarEvents} from './GoogleCalendarEvents';

    componentWillMount(){
      var myitems = getCalendarEvents( (resp) => {
        console.log(resp)
      }); 
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! That's what i was looking for. Very clean and simple. So "callback" is a kind of function that returns "resp" as value, isn't it?
@oklas, it would have been better if you mark that ques as duplicate instead of providing a new answer, because the same ques has been answered very very well in that link :)
I have not read or search such evident for me info so i do not know about another question like this. So i just write. I have not such rights to make duplicate yet. There is no problem to visiters of this page, they will see duplicate reference and will go to read there. It is strange to prevent me write answer the question.
@oklas no one is preventing you to write answers, its a open platform you can answer any ques, but answering a duplicate ques that has been answered very well, is not required :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.