我怎样才能返回承诺和数据?

时间:2015-08-12 13:55:28

标签: javascript angularjs

我在javascript(typescript)中有这个功能:

getRole = () => {
    return this.getData(EnumGetData.Role)
        .then((data) => { 
            this.role = data;
            // I want to do something with data here which is why 
            // I have the .then 
        });
}

以下是我如何调用该函数:

return enumService.getRole()
    .then((results): void => {
       // I want to do something here with results
    });

该功能有效,但同时返回成功或失败我还想返回数据

有人可以告诉我如何做到这一点吗?

1 个答案:

答案 0 :(得分:1)

似乎很容易

getRole = () => {
    return this.getData(EnumGetData.Role)
        .then((data) => { 
            this.role = data;
            // I want to do something with data here which is why 
            // I have the .then 
            // "I would like to also return data"
            return data;
        });
}

重新阅读问题后,我可能误解了......你想让getRole返回Promise AND数据吗?如果是这样,那么你不能这样做,因为如果this.getData是异步的,那么getRole不能返回data(忽略函数返回单个值的事实)

与流行的误解相反,Promise不会使异步代码同步

(通过下面的评论,我发现我并没有误解你的问题,而且你已经掌握了Promise的工作方式)

但是,如果你要

getRole().then(function(x) { 
    console.log(x); 
});

你会在上面的代码中找到x ==数据

相关问题