【问题标题】:How do promise chains work?承诺链如何运作?
【发布时间】:2014-11-24 00:29:54
【问题描述】:

我在 SO 中找到了以下代码,我尝试对其进行调试以更好地理解 promise 概念,目前在下面的代码中有一些我不理解的东西,这就是为什么最后一个然后得到id==4 的值(在 specificTweet 中)而不是所有推文列表?

$.get('profile.json').then(function (profile) {

    return $.get('tweets.json').then(function (response) {
        return response.filter(function (tweet) {
            //this is return that not related to the promise just to the filter
            return tweet.id === 4;
        });
    });

}).then(function (specificTweet) {

...

这是 JSON 文件,

[
  {
   "id": 1,
   "tweet": "OMG, worst day ever, my BF @BobbyBoo dumped me",
   "usersMentioned": [
     {
      "id": 10,
      "username": "BobbyBoo"
     }
    ]
  },
  {
   "id": 2,
   "tweet": "OMG, best day ever, my BF came back to me"
  },
  {
   "id": 3,
   "tweet": "OMG, worst day ever, just don't ask"
  },
  {
   "id": 4,
   "tweet": "@BobbyBoo OMG...just OMG!",
   "usersMentioned": [
     {
      "id": 10,
      "username": "BobbyBoo"
     }
    ]
  }
]

【问题讨论】:

    标签: javascript jquery json promise angular-promise


    【解决方案1】:

    当您创建这样的代码时:

    doSomething().then(function (result1) {
        return 'foo';
    }).then(function (result2) {
        console.log(result2 === 'foo');    // this logs "true" to the console
    });
    

    您正在创建一个承诺链。每个.then() 创建一个新的promise,它要么在原始promise 被解析并且成功处理程序完成时被解析,要么在原始promise 被拒绝并且失败处理程序完成时被拒绝。新的承诺将“包含”最后一个成功/失败处理程序返回的数据。因此,因为代码示例中第一个.then() 中的成功处理程序返回过滤后的推文,所以第二个.then() 中的成功处理程序(第二个.then() 调用从第一个.then() 返回的承诺)将收到过滤列表,而不是原始列表。

    你最好只是see the documentation

    但是,代码示例中有一个小错误。第二个处理程序不会只接收特定的推文,它会收到一个仅包含该推文的列表。

    【讨论】:

      【解决方案2】:

      尝试反过来评估它,从下到上。当您链接 then 调用时,以下表达式的结果始终传递给上述表达式。

      4..then(function (specificTweet)

      3.return response.filter(function (tweet) { -> 过滤推文并在上面传递结果

      2.return $.get('tweets.json').then(function (response) -> 在上面传递推文

      1.$.get('profile.json') -> 将配置文件传递到上面

      【讨论】:

        猜你喜欢
        • 2019-08-29
        • 2019-05-24
        • 2017-11-23
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 2012-07-17
        • 2015-11-08
        相关资源
        最近更新 更多