从React中的回调函数返回值

时间:2017-05-24 09:26:25

标签: javascript reactjs asynchronous

我在外部文件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);
            };

          });
        });
      }

我需要在输入js文件中使用“resp.items”值:

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

我该怎么做?我知道有很多回复,但我想了解我的例子中的异步模式。

1 个答案:

答案 0 :(得分:1)

在文件中重写您的函数,如下所示:

    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)
      }); 
    }