组合angularjs中的2个承诺

Combining 2 promises in angularjs

本文关键字:承诺 2个 中的 angularjs 组合      更新时间:2023-09-26

我组合了两个承诺,但不起作用,在一个服务中,我有两个方法,其中方法"UserService.getAuthenticatedUser()"获得当前用户信息,然后有一个"UserService.getAccountTypeData(idUser)",其中获得用户类型信息,但要获得第二个方法,我需要用户ID,所以基本上首先我调用"UserService.jetAuthenticateduser()",获取id,然后调用"UserService.getAccountTypeData(idUser)",但不起作用。

 function isAccount(accountName) {
             UserService.getAuthenticatedUser()
                .then(function (response) {
                    var userDetails = response.data;
                });

            UserService.getAccountTypeData(idUser)
                .then(function (response) {
                    var userDetails = response.data;
                    return  userDetails;
                });
}

附言:我已经注入了服务。。。

您可以通过返回.then()函数的值来连锁您的承诺。

function isAccount(accountName) {
    return UserService.getAuthenticatedUser(accountName) // pass in accountName argument?
        .then(function(response) {
            var userDetails = response.data;
            return userDetails.Id; // user id value
        })
        .then(UserService.getAccountTypeData) // userDetails.Id gets passed to getAccounttypeData method
        .then(function(response) {
            var userDetails = response.data;
            return userDetails;
        });
}
// usage
isAccount('AccountA').then(function(userDetails) {
    // do something with userDetails
});

您正在处理异步调用,因此当您调用.then()方法时,它将执行该函数,并将回调连接到作为参数传递给then()的匿名函数。如果第二个依赖于第一个,你可以这样嵌套它们。。。

function isAccount(accountName) {
      UserService.getAuthenticatedUser()
         .then(function (response) {
             var userDetails = response.data;
             UserService.getAccountTypeData(idUser)
                .then(function (response) {
                    var userDetails = response.data;
                    return  userDetails;
                });
         });
}