1

What is a clean way to write a code like this? For multiple times I have to use the response of previous request to build a new URL and elastic search query from different sources and tables.

$scope.whatIFinallyWant = {};
$http.get(url1).then(function(response1){
    // creating new url2 & query with response1
    $http.get(url2).then(function(response2){
        // creating new url3 & query with response2
        $http.get(url3).then(function(response3){
            // creating new url4 & query with response3
            $http.get(url4).then(function(response4){
                // using the final response in UI ... 
                $scope.whatIFinallyWant = response4;
            }) 
        }) 
    }) 
})
1
  • synchronous promise - Promises are asynchronous by design Commented May 25, 2017 at 23:04

2 Answers 2

2

Chain the promises like so

$scope.whatIFinallyWant = {};
$http.get(url1)
.then(function(response1) {
    // creating new url2 & query with response1
    return $http.get(url2);
}).then(function(response2) {
    // creating new url3 & query with response2
    return $http.get(url3);
}).then(function(response3) {
    // creating new url4 & query with response3
    return $http.get(url4);
}).then(function(response4){
    // using the final response in UI ... 
    $scope.whatIFinallyWant = response4;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Since $http.get() returns resolved data ( please checkout angular docs for it's exact shape: https://docs.angularjs.org/api/ng/service/$http), you might use predefined function to form url and call $http.get():

let makeUrl = (promiseResult) => {
  let url
  /* some logic */
  return $http.get(url);
}

let logErr = (err) => {
    console.error("Whoops! " + err);
}

$http.get(url1)
  .then(makeUrl)
  .then(makeUrl)
  .then(makeUrl)
  .then((finalUrl) => {
     $scope.whatIFinallyWant = finalUrl;
  })
  .catch(logErr)

2 Comments

everytime the logic to create a new url and query is very different. not possible to use a function for all of those processes.
also, $scope.whatIFinallyWant will be a promise, rather than response4

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.