2

I have an array of url and the requirement is that I have to make http.get requests in a synchronous manner. Only after the first url call is successful, the second one should be called

for(var i in urlArray)
{
    /*do some operations and get the next url*/
    $scope.alpha(newURL);
}

$scope.alpha = function (newURL) {
    $http.get(newURL) // these calls should be synchronous
    .success(function () {
    })
    .error(function () {
    });
}

How do I do this?

1
  • did you try using $q ? Commented Jul 8, 2015 at 13:11

2 Answers 2

2

It seems what you really want to is make the calls sequentially, not necessarily synchronously.

In that case, don't use a loop (because it's synchronous). Simply make the next call in response to the previous call.

Simplified example:

var i = 0;
makeRequest(urlArray[i], function success() {
  var nextURL = urlArray[++i];
  if (nextURL) {
    makeRequest(nextURL, success);
  }
});

where makeRequest is the function that makes the Ajax request and calls the callback on success:

function makeRequest(url, callback) {
    $http.get(url).success(callback);
}
Sign up to request clarification or add additional context in comments.

4 Comments

how do i define makeRequest? the syntax, I mean.... with the above code, I am getting "ReferenceError: makeRequest is not defined"
Just like you define any other function, e.g. function makeRequest(url, callback) { ... }. You can name it whatever you want, this is just an example.
Well, you have to replace the ... with the code of the function.
There, I updated my answer. I didn't expect defining the function to be such a big problem.
1

I am assuming that you want call them sequentially, in that case, you can use something like a recursion, call the function inside the .success callback

var currentURL; // calculate teh currentURL
$scope.alpha(currentURL);

$scope.alpha = function (newURL) {
    $http.get(newURL) // these calls should be synchronous
    .success(function (response, status, headers, config) {
        //get the response
        //generate the new currentURL as per your need

        //keep a break condition, to exit
        $scope.alpha(currentURL);

    })
    .error(function () {
    });
}

2) alternately you can you $q, deferred calls to achieve this

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.