Make a set of recursive HTTP GET calls and wait for them all

I have a REST service offering a list of "Json" objects, and each object can have a link to another resource of its class. Starting with a specific one, I need to get them all by making a recursive HTTP call. Therefore, I wrote:

var steps = [];
var recursiveLookup = function(processId) {
  return $.ajax({
    url: SERVER_URL + processId,
    success: function (activity) {
      // Activity has a set of json objects called steps
      var rtn = activity.path.map(step => {
        if (step.type != "Node") {
          steps.push(step);
        } else {
          return recursiveLookup(step.subProcessIntanceId);
        }
      }).filter(a => a != undefined);
      return rtn;
    }
  });
}

This would correctly load all objects into the var global steps. I have to be sure that the method is finished, so I wrote:

var promises = recursiveLookup(processId);
Promise.all(promises).then(function () {
   console.log(steps);
});

But it does not work, because "recursiveLookup" returns the promise of $ .ajax instead of a set of promises pretending to be returned using the success method.

Also, is it possible to get steps as a return value from the "recursiveLookup" method, using it as a global variable?

+4
source share
2

-, , , :

var recursiveLookup = function(processId,steps=[]) {
  return $.ajax({
    url: SERVER_URL + processId,
  })
  .then(
    function (activity) {
      // Activity has a set of json objects called steps
      steps = steps.concat(
        activity.path.filter(
          step => step.type !== "Node"
        )
      );
      return Promise.all(
        activity.path.filter(
          step => step.type === "Node"
        )
        .map(
          step=>
            recursiveLookup(step.subProcessIntanceId,steps)
        )
      ).then(
        result=>steps.concat(result)
      )
    }
  );
}

, , , , .

+1

, promises. , , - , .

function request(page) {    
// return the AJAX promise
return $.ajax({
    url: '/echo/json/',
    method: 'POST',
    dataType: 'json',
    data: {
        delay: 1,
        json: JSON.stringify(ret)
    }
 });
}

function requestOddsFrom(page, items) {
return request(page).then(function(data){
    if (data.currentPage > data.totalPage) {
        return items;
    } else {
        var filtered = data.items.filter(function(el){ return el%2 == 1; });
        return requestOddsFrom(data.currentPage + 1, items.concat(filtered));
    }
 });
}

function requestAll(){
return requestOddsFrom(1, []);
}

 requestAll().then(function(items) {
   console.dir(items);
});

jQuery AJAX Call Promise

?

-2

Source: https://habr.com/ru/post/1691500/


All Articles