0
我正在使用異步庫(http://caolan.github.io/async/docs.html#map)來處理節點應用程序中的一些異步調用。我的問題是,當我使用異步的映射方法時,在完成所有迭代函數之前調用方法的回調函數。有人知道爲什麼在迭代函數完成之前調用異步回調
這裏就是地圖被調用的代碼:
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)
});
})
})
}
而這裏的iteratee代碼調用每個項目在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)
}
}
})
}
最後,這裏是輸出到控制檯:
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
有點上下文:我使用map來檢索日曆事件列表Google日曆的API。
謝謝!
嘗試,並把'的console.log(「達到iteratee函數中調用回調」)'之初'getEventsUpTo'函數。此外''callback(true)'行在錯誤的地方。 – SpiderPig