2014-10-29 112 views
2

我有myPeople功能,即在它调用这样使用蓝鸟承诺

var myPeople = function(){ 
    var go; 
    return new Promise (function(resolve){ 
     User 
      .getPeople() 
      .then(function(allPeople){ 
       go = allPeople; 
       //console.log(go) 
       resolve(go); 
      }) 
     }) 
    return go; 
} 

一个承诺的功能,如果我登录块让我的对象之内我去,但我不能让它返回这个对象..

+1

你需要在返回的promise上使用'then'方法,而不仅仅是'getPeople'方法 – 2014-10-29 18:42:02

+0

有没有办法让myPeople返回对象本身作为'{.. ..}'我可以使用这种方式,我不必'myPeople()。然后(在这里做一些事情);'? – goms 2014-10-29 18:49:26

+0

@goms不,没有。这是因为那样就没有办法知道该方法实际上是在执行异步操作。 – 2014-10-29 19:12:50

回答

2

链的承诺,也 - 避免then(success, fail)反面模式:

var myPeople = function(){ 
    return User.getPeople() 
      .then(function(allPeople){ // 
       console.log(allPeople); 
       return allPeople.doSomething(); // filter or do whatever you need in 
               // order to get myPeople out of 
               // allPeople and return it 

      }); 
     }); 
} 

然后在外面:

myPeople.then(function(people){ 
    console.log(people); // this will log myPeople, which you returned in the `then` 
}); 
+0

Ben,我得到你说的,但在外面,想用myPeople返回的对象以及其他东西,这就是为什么我不需要将所有东西都嵌套在myPeople.then()之下。 – goms 2014-10-29 19:09:42

+0

@goms承诺使用函数执行异步操作_cannot_直接返回值。它必须承诺超过这个价值,你必须打开它。 – 2014-10-29 19:11:01

+0

您可能想要[阅读此答案](http://stackoverflow.com/a/16825593/1348195)以获取JS中的异步性。 – 2014-10-29 19:12:23