jquery用循环多重依赖关系链接ajax

时间:2018-01-01 14:22:04

标签: jquery ajax

我需要链接3个ajax调用,并且每个调用都会返回下一个调用所需的数组。这是我的代码:

function getCompanies(){
   return $.ajax({
    url :'.../GetCompanies'
   });
}

 function getDepartments(companyid){
   return $.ajax({
    url :'.../GetDepartments/companyid'
   });
}

 function getEmployees(deptid){
   return $.ajax({
    url :'.../GetEmployees/deptid'
   });
}

function GetAll(){
 $.when(getCompanies()).done(function(data){                            
    $.each(data, function(index, value){
            console.log(value.name); //company name 
        $.when(getDepartments(value.id)).done(function(data){
           $.each(data, function(index, value){     
                console.log(value.name); //department name                              
                $.when(getEmployees(value.id)).done(function(data){ 
                    $.each(data, function(index, value){                                    
                    console.log(value.name); //employee name
                    });                                             
                .......

我的问题是输出是这样的:

     Company 1 
     Company 2
     Company 3
     Dept 1 ( of company 1)
     Employee 1
     Employee 2 
     Dept 2 ( of company 1)
     ....

我需要它:

    Company1
    Dept 1 ( of company 1)
    Employee 1
    Dept 2 ( of company 1)

    Company 2
    Dept 1 ( of company 2) 

另外我需要拨打所有3个api,没有别的办法解决这个问题。 提前致谢。

2 个答案:

答案 0 :(得分:0)

我相信这样的事情会起作用。



function getCompanies() {
  return $.ajax({
    url: '.../GetCompanies'
  });
}

function getDepartments(companyid) {
  return $.ajax({
    url: '.../GetDepartments/companyid'
  });
}

function getEmployees(deptid) {
  return $.ajax({
    url: '.../GetEmployees/deptid'
  });
}

function GetAll() {
  function processCompanies(companies) {
    if (companies.length) {
      var company = shift(companies); //pop the first company off the array

      console.log(company.name);

      //get the departments for the company and process them
      getDepartments(company.id).then(function(departments) {
        processDepartments(companies, departments);
      });
    }
  }

  function processDepartments(companies, departments) {
    if (departments.length) {
      var department = shift(departments); //pop the first department off the array

      console.log(department.name);

      //get the employees for the department and process themm
      getEmployees(department.id).then(function(employees) {
        $.each(employees, function(index, employee) {
          console.log(employee.name);
        });
        
        //we have now processed all the employees for this department
        //process the next department
        processDepartments(companies, departments);
      });
    } else {
    	//there are no more departments in this company
      //process the next company
      processCompanies(companies);
    }
  }

  getCompanies().then(processCompanies);
}




答案 1 :(得分:0)

这是一个很平坦的例子,说明你要做什么。

它基于live API存储用户,虚拟博客帖子和这些帖子的评论。

以下获取用户集合,然后获取每个特定用户的所有帖子,然后获取每个特定帖子的所有评论

最终结果是所有请求都在最后完成,getUsers()回调中的最终用户集合将所有帖子和注释嵌套到每个用户中

由于嵌套级别相同,因此翻译各种方法以匹配您的方法应该相当容易

var baseUrl = `https://jsonplaceholder.typicode.com/`

function getUsers() {
  return $.ajax({
    url: baseUrl + 'users?_limit=3'
  }).then(function(users) {
    //returns promise of getting all posts for all users
    // all the posts also return promises below to get comments for each post
    return getAllPosts(users).then(function() {
      return users // return the users when all the other promises have resolved
    });
  })
}
// makes request for posts for an individual user
function getUserPosts(user) {
  var url = baseUrl + `posts?_limit=3&userId=${user.id}`
  return $.ajax({
    url: url
  }).then(function(posts) {
     // assign posts to current user
     user.posts = posts;
     return posts;
     // returns promise to get comments for these posts
  }).then(getAllPostsComments)
}
// makes request for comments for an individual post
function getPostComments(post) {
  var url = baseUrl + `comments?_limit=3&postId=${post.id}`
  return $.ajax({
    url: url
  }).then(function(comments) {
    post.comments = comments// assign comments array to the specific post
  });
}
// creates promise array for all users posts requests
function getAllPosts(allUsers) {
  var postPromises = allUsers.map(getUserPosts)
  return Promise.all(postPromises)
}
// creates promise array for specific user's posts comments
function getAllPostsComments(userPostsArray) {
  var postPromises = userPostsArray.map(getPostComments);
  return Promise.all(postPromises)
}

// now get all the data
getUsers().then(function(users) {
  // all the posts and post comments are nested in each user object here
  console.log(users)
  

}).catch(err=>console.log('error occured in promise chain', err))
.as-console-wrapper {	max-height: 100%!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>