嵌套的依赖回调函数

时间:2018-08-31 10:01:15

标签: javascript callback nested

我对回调地狱还是很陌生的(但现在我越来越了解它的含义了)

设置:

  • getAccessToken:调用以从api获取访问令牌
  • getUserID:具有访问令牌,可从api获取用户ID
  • getUserDetails:使用userID从api获取用户详细信息
  • postUserDetails:将检索到的用户详细信息发布到api

我需要在调用中传递值:

  

getAccessToken 令牌-> getUserID(令牌)用户ID   -> getUserDetails(userID) userDetails -> postUserDetails(userDetails)

在我幼稚的时候,我想我可以像这样运行某事:

postUserDetails(getUserDetails(getUserID(getAccessToken())));

或反过来(我需要更改命名约定,但是我尝试了太多,以至于最终陷入了下面的纠结之中

getAccessToken(getUserID(getUserDetails(postUserDetails)))

在异步ajax调用正常工作的情况下,获得类似于以下内容的逻辑结构是什么?如何传递多个从上一次调用中获取值的回调?

我是否依靠任何框架(例如异步)使postUserDetails(getUserDetails(getUserID(getAccessToken())))工作?

1 个答案:

答案 0 :(得分:1)

  

我需要在示例getAccessToken-> getUserID-> getUserDetails-> postUserDetails的调用中传递值,我不清楚我的问题是否清楚

是的,价值,但诺言本身。

您的代码的简单模拟:

//your call chain
getAccessToken()
  .then(getUserID)
  .then(getUserDetails)
  .then(postUserDetails)
  .then(() => {
    console.log("Done");
  })

//a mock of your code

//a utility to "simulate" the delay of a server call and return a Promise
function wait(delay) {
  return new Promise(resolve => setTimeout(resolve, delay));
}

function getAccessToken() {
  console.log("getAccessToken");
  //mock the request to the server
  return wait(Math.random() * 1000+500)
    .then(() => {
      console.log("generating a token");
      return Math.random().toString(36).slice(2)
    });
}

function getUserID(token) {
  console.log("getUserID(%o)", token);
  //mock the request to the server
  return wait(Math.random() * 1000+500)
    .then(() => {
      console.log("returning userId");
      return "id-1234";
    });
}

function getUserDetails(userId) {
  console.log("getUserDetails(%o)", userId);
  //mock the request to the server
  return wait(Math.random() * 1000+500)
    .then(() => {
      console.log("returning user");
      return {
        id: userId,
        firstName: "Zaphod",
        lastName: "Beeblebrox"
      }
    });
}


function postUserDetails(user) {
  console.log("postUserDetails(%o)", user);
  return wait(Math.random() * 1000+500)
    .then(() => {
      console.log("userDetails posted");
    });
}
.as-console-wrapper{top:0;max-height:100%!important}