我在使用 Q 和 reduce 惯用法串联运行多个前提时遇到问题(请参阅: http://taoofcode.net/promise-anti-patterns/ )
我尝试遵循这个例子,稍微改变一下,这就是我得到的:
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());
});
现在,我可能应该谈谈这背后的主要思想:
1) 我正在创建一个 YouTube 播放列表。从 createPlaylist 函数中,我返回一个包含播放列表 ID 的 promise ,然后
2) 对于我拥有的每个 SongInfo,我需要在 YouTube 模块上调用搜索方法。搜索功能也需要回调。在这种情况下,如果正确找到/解析了所需的歌曲,我将调用 addSongToPlaylistMethod。正如您所看到的,addSongToPlaylist 还返回一个 Promise。
现在,问题是: 里面的所有 block
then
方法,调用于
累积前提
仅执行一次。
您可能会问我为什么在这种情况下不使用 forEach ?嗯,因为 http://www.acnenomor.com/3037813p1/playlistitems-batch-insert-youtube-api-v3
你能帮我解决一下吗?
干杯, 斯拉维克
最佳答案
您没有从reduce函数返回任何内容。
accumulatedPremise.then(function (response) {
应该是:
return accumulatedPremise.then(function (response) {
关于javascript - 系列 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27750537/