根据我迄今为止的研究,我相信我正确使用了 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);
}