使用蓝鸟承诺

时间:2014-10-29 18:40:21

标签: javascript node.js promise bluebird

我有myPeople函数,在其中调用这样的promise函数

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 个答案:

答案 0 :(得分: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`
});