Reputation: 1919
I have problem running multiple premises in series, using Q and reduce idiom (see: http://taoofcode.net/promise-anti-patterns/)
I tried to follow this example, change it a little bit and here's what I've got:
playlist.createPlaylist('playlist')
.then(function(playlistId) {
songsInfo.reduce(function (accumulatedPremise, songInfo) {
accumulatedPremise.then(function (response) {
var def = Q.defer();
youtube.search(songInfo, function (songInfo, resp) {
var song = songParser.parse(songInfo, resp);
if (song !== null) {
playlist.addSongToPlaylist(song, playlistId).then(function(response) {
def.resolve(response)
})
}
});
return def.promise;
})}, Q());
});
Now, I should probably talk a little about main idea behind this:
1) I'm creating a youtube playlist. From createPlaylist function, I'm returning a promise with playlist's ID and then
2) for each SongInfo I have I need to invoke search method on my youtube module. Search function also takes a callback. In this case, I'm invoking addSongToPlaylistMethod if desired song was found/parsed correctly. As you can see, addSongToPlaylist also returns a Promise.
Now, the problem: all the block inside
then
method, invoked on
accumulatedPremise
is executed only once.
You could probably ask me why simply not to use forEach in this case? Well, because of http://www.acnenomor.com/3037813p1/playlistitems-batch-insert-youtube-api-v3
Could you please help me fixing it?
Cheers, Slawek
Upvotes: 2
Views: 348
Reputation: 18569
You're not returning anything from the reduce function.
accumulatedPremise.then(function (response) {
should be:
return accumulatedPremise.then(function (response) {
Upvotes: 3