0

I've got an array of angularjs $http config objects:

    var steps= [
    {url:"http://api.com/test1", method: "GET"},
    {url:"http://api.com/test2",method: "POST"},
    {url:"http://api.com/test3",method: "GET"},
 ]

These are all API calls I need to execute in sequence. The number of this calls can vary.

I would like transform each of this object in a function executing the $http call (so then I can use that with map to obtain an array of functions).

Something like:

function transform(conf){
   return $http(conf);
}

But this, obviously, executes the $http call.

Atropo
  • 12,231
  • 6
  • 49
  • 62
  • `execute in sequence` and using `$q.all` - not clear on this aspect. Do you want to send calls in parallel or in sequence? – Nikhil Aggarwal Nov 06 '18 at 10:19
  • I want to execute the calls in sequence – Atropo Nov 06 '18 at 10:26
  • You can do `let transform = (conf) => () => $http(conf);` to get a function that returns a promise, which you can execute later. But it's still unclear what you want to do after that - you say you want to execute them in sequence, but you mention `q.all` which will execute them in parallel. – Frank Modica Nov 06 '18 at 10:36
  • Edited the question, removed the reference to `$q.all()` that was wrong. – Atropo Nov 06 '18 at 10:38
  • you just made my day... `return new Function('$http', 'return $http(config)');` – GottZ Nov 06 '18 at 10:40

2 Answers2

2

You can use Array.reduce to chain the promises.

let promise =  steps.reduce((promise, step) => promise.then(() => $http(step)), $q());

ES5

let promise =  steps.reduce(function(promise, step){
     return promise.then(function(){
        return $http(step);
    });
}, $q());
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2

One option is to use the async/await pattern where you can await in the loop of request which would make them execute in a sequence.

Try it like this

app.controller('yourControllerController', 
    async function($scope, $http) {

    var steps = 
    [
        { url:"http://api.com/test1", method: "GET" },
        { url:"http://api.com/test2", method: "POST" },
        { url:"http://api.com/test3", method: "GET" },
     ];

    async function processHttpRequests(){
        for(const step of steps){
            var result = await $http({ method: step.method, url: step.url});
            console.log('Url:' step.url + ' Result: ' + result);
        }
    }; 

    await processHttpRequests();
});
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69