简体   繁体   中英

Async callback being called before iteratee functions complete

I'm using the async library ( http://caolan.github.io/async/docs.html#map ) to handle some of my asynchronous calls in a node application. My problem is that when I use async's map method, the method's callback is being called before all the iteratee functions are completed. Anyone know why?

Here's the code where map is being called:

function divvy(email, project, oauth2Client, callback) {
  getUserPreferences(email, (preferences) => {
    calendars.getCalendars(oauth2Client, (calendars) => {
      var calendarIds = calendars.map(function(obj) { return obj.id })
      console.log('length of calendarIds is: '+calendarIds.length)
      asyncMap(calendarIds, events.getEventsUpTo.bind(null, project.end, oauth2Client), function(err, results) {
        // results is now an array of arrays. 
        // Each array within results is an array of events per calendarList
        console.log('final callback is called')
        callback(true)
      });
    })
  })
}

And here's the iteratee code being called for each item in calendarIds:

function getEventsUpTo (projectEnd, oauth2Client, calendarId, callback) {
  calendar.events.list({
    auth: oauth2Client,
    calendarId: calendarId,
    timeMin: (new Date()).toISOString(),
    timeMax: projectEnd.toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, response) => {
    if (err) {
      // console.error('The API returned: ' + err)
      console.log('reach callback call within iteratee function')
      callback(null, null)
    } else {
      var events = response.items
      if (events.length === 0) {
        callback('No upcoming events')
      } else {
        console.log('reach callback call within iteratee function')
        callback(null, events)
      }
    }
  })
}

Finally, here's the output to the console:

length of calendarIds is: 6
reach callback call within iteratee function
reach callback call within iteratee function
reach callback call within iteratee function
final callback is called
reach callback call within iteratee function
reach callback call within iteratee function

A bit of context: I'm using map to retrieve lists of calendar events from Google Calendar's API.

Thanks!

You return true, when all the callbacks where registered . You need callbacks that execute your callback:

var counter=0;
function call(number=-1){
  counter +=number;
  if(counter==0){
  alert("finished");
  }}

And on your async funcs do:

call(1);
registercallback(()=>{call()});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM