Bishal Jain
Bishal Jain

Reputation: 209

handling multiple http call and multiple response

I have an object with multiple key value pair and each key value pair need to send as a request and obviously I will have multiple response with some success and some of them as error. Now how to handle them as I have to handle partial success and failure case:

requestParams = {0:'value1',1:'value2',2:'value3'}

Now each of the value inside requestParams need to send a http request and respective response need to handle properly.

I want to

for(i=0;i<requestParams.length;i++){
     http.get(url,requestParams[i]).then(resolve,reject)

and for both success and reject some alert need to display so how can I handle that? Thanks.

Upvotes: 2

Views: 357

Answers (1)

Mark
Mark

Reputation: 92461

You need to use Promise.all to process a set of promises. The problem is a single failure will cause the Promise.all to fail. You can place a catch() on the individual promises from http.get() and return something into the stream. Since catch() returns a fresh non-rejected promise, Promise.all doesn't know there was a failure. You can then filter on that to find individual errors.

For example here's a fake http.get that fails once:

// Faked HTTP object
let http = {
  get(url) { // will fail for 'value2'
    return url == 'value2' ? Promise.reject("some error for: " + url) : Promise.resolve("some value for: " + url)
  }
}

let arr = ['value1', 'value2', 'value3']
let promises = arr.map(item =>
  http.get(item)
  .catch(e => "ERROR: " + e) // catch error here, returning a value or error to be processed later
)
Promise.all(promises).then(console.log)

Upvotes: 2

Related Questions