【问题标题】:Promises in series一系列承诺
【发布时间】:2015-01-03 09:31:58
【问题描述】:

我在串联运行多个前提时遇到问题,使用 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 的承诺,然后

2) 对于我拥有的每个 SongInfo,我需要在我的 youtube 模块上调用搜索方法。搜索功能也需要回调。在这种情况下,如果正确找到/解析了所需的歌曲,我将调用 addSongToPlaylistMethod 。可以看到,addSongToPlaylist 也返回了一个 Promise。

现在,问题: 里面的所有方块

then

方法,调用于 accumulatedPremise 只执行一次。

您可能会问我为什么在这种情况下不使用 forEach?嗯,因为 http://www.acnenomor.com/3037813p1/playlistitems-batch-insert-youtube-api-v3

你能帮我修一下吗?

干杯, 斯拉维克

【问题讨论】:

  • 看起来不太“有前途”(LOLZ 有意)。看起来您将回调地狱混合在一个 promise then 函数中?由于 Promise 旨在防止回调地狱,因此请使用 Promise 而不是嵌套回调。 Q 的 nfcall() 函数对此做了规定。
  • 谢谢。不推荐使用 nfcall 吗?我不应该改用 ninvoke 吗?

标签: javascript node.js promise q


【解决方案1】:

你没有从 reduce 函数返回任何东西。

accumulatedPremise.then(function (response) {

应该是:

return accumulatedPremise.then(function (response) {

【讨论】:

  • 是的,就是这么简单......当你盯着代码看了一个小时却错过了类似的东西时的那种感觉......谢谢!
猜你喜欢
  • 2016-09-02
  • 2018-10-03
  • 2013-10-23
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 2016-02-01
  • 2015-04-09
相关资源
最近更新 更多