2014-11-23 62 views
0

我在SO中发现了下面的代码,为了更好地理解promise的概念,我尝试调试它,目前有一些我在下面的代码中不理解,这就是为什么最后得到的值(在特定的Twitter)与id == 4,而不是所有的推文列表?承诺链如何工作?

$.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" 
    } 
    ] 
    } 
] 

回答

1

当您创建一个像这样的代码:

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

你要创建一个承诺链。每个.then()创建一个新的承诺,当原始承诺解决时,以及当原始承诺被拒绝并且失败处理程序完成时成功处理程序完成或拒绝时,解决此问题。新承诺将“包含”上次成功/失败处理程序返回的数据。所以,因为在第一.then()成功处理程序的代码示例中返回筛选鸣叫,成功处理程序在第二.then()(第二.then()被称为从第一.then()返回的承诺)将接收到的过滤列表,而不是原来的列表中。

你最好只是see the documentation

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

1

尝试从下往上评估它。当您连接then调用时,下面表达式的结果总是传递给上述表达式。

4. .then(function (specificTweet)

3.​​- >过滤器鸣叫,并通过导致上述

2. return $.get('tweets.json').then(function (response) - >通过上述

1. $.get('profile.json')鸣叫 - >简档传递到上述