代码之家  ›  专栏  ›  技术社区  ›  barteloma

如何按顺序解析嵌套的$q.all

  •  0
  • barteloma  · 技术社区  · 6 年前

    我有两个承诺函数, getToken() getUser(token) 在我的angularjs项目中。

    $q.all({token: getToken(), userId: getUserId()})
    .then(function(resolutions){
      var token  = resolutions.token;
      var userId = resolutions.userId;
    });
    

    但是我的 getUserId() 方法将令牌作为参数。所以我需要先得到token,然后得到userId并返回token和userId。我如何使用 $q ?

    我以前是这样的:

    return getToken().then(function(token){
          return getUserId(token).then(function(userid){
                return {token: token, userid: userid};
          })
    })
    

    但不起作用,userid为空。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Nikhil Aggarwal    6 年前

    你可以像下面这样连环承诺

    getToken()
    .then(function(token){
         return getUser(token)
         .then(function(userId){
              return {token, userId};
          })
    })