根据我迄今为止的研究,我相信我正确地使用了async.each。底部函数addToPlaylist调用顶级函数getPerformances。我试图弄清楚为什么没有调用addToPlaylist中的最终回调以及如何修复它。谢谢!
var getPerformances = function(playlist, performances, add){
var deferred = Q.defer();
var tracks = [];
async.each(performances.performance, function(performance, cb) {
getSpotifyArtistId(performance.artist.displayName).then(function (artistId) {
if (add == true) {
getTopTracks(artistId).then(function (trackstoAdd) {
tracks.push.apply(tracks, trackstoAdd);
cb();
});
} else {
//Other stuff... only looking at the true option at this point
}
});
}, function(err){
if( err ) {
console.log(err);
deferred.resolve(tracks);
} else {
deferred.resolve(tracks);
}
});
return deferred.promise;
}
问题在于 - 如果cb()在then()内,则不会调用最终回调。如果CB被移到promise回调之外,则调用finalCallback,但当然,它被调用得太快了。
var AddToPlaylist = function (playlist, results) {
var allSongs = [];
var handler = function (performances, cb) {
getPerformances(playlist, performances, true)
.then(
function (trackstoAdd) { // all is well!
allSongs.push.apply(allSongs, trackstoAdd);
//console.log(allSongs) is as expected
cb();
}
,
function (err) { // something bad happened!
cb(err);
}
);
}
var finalCallback = function () {
console.log('test');
}
async.each(results, handler, finalCallback);
}