0

in a Node.JS app, I am trying to make 3 API calls to different endpoints, which are:

/GET ProductInformation : returns the information for the given productID.

/GET ProductRecommendation : returns the product recommendation for the given productID

/GET ProductReview : returns product reviews and rating for the given productID

None of the above call is dependent on the other, therefore, if possible, I am trying to avoid a chain of Promise like :

getProductInfo(productId)
.then(result =>{
      getProductRecommendation(productId)
.then(result =>{
      getProductReview(result => {
      callback('done') // all calls are done, we can return now!
     })
})

Is there a better approach for making this sort of async operations ? The reason that I am looking to see if there is a better way or not, is because in reality I have more than just 3 calls, and doing this makes the code hard to maintain and read.

1 Answer 1

5

Promise.all will run these all in parallel. If any of the promises fail it will go to .catch().

Promise.all([
  getProductInfo(productId),
  getProductRecommendation(productId),
  getProductReview()
])
.then(function(results){callback('done')})
.catch(err=>console.log(err));
Sign up to request clarification or add additional context in comments.

4 Comments

would it be possible to still return in case of partial failure? example, 1 out of the 10 services failed to respond.
Possibly, I need to test it real quick before I post something
You can do something like getProductInfo(productId).catch(err=>console.log(err)) and it will continue on to .then(), but doing something like "1/10" is more complicated. If you need more fine grain control I would look into async/await and try{}catch(e){} on each api call. --- or a promise library that will help orchestrate some of this. repl.it/@CodyGeisler/…
Promise.allSettled() will give you an array that tells you the results.

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.