andreboekhorst
andreboekhorst

Reputation: 31

Functional programming with nested promises

In an Angular project, I'm working on a booking system with a lot of different scenarios. Based on the response of a promise, it should try to make a different call to the server. This results in a sort of callback-hell of which I thought promises can prevent me from: functions don't return anything but initiate another function.

Here is a simplified decision tree:

My code looks something like this:

makeBooking()
.then(function(response){
     succesHandler(response);
}, function(error){
    errorHandler(response);
})

succesHandler(response){
    loadDetails(response)
      .then(function(details){
          showDetails(details);
    }, function(error){
          handleDetailsError(error);
    }
 }

 errorHandler(response){
     if ( checkSoldout(reponse) ){
          makeAlternativeBooking();
     }
 }

Is this a good (function) way to work with these 'nested' promises?

Upvotes: 0

Views: 112

Answers (1)

mido
mido

Reputation: 25034

your flow diverges at each point, not much changes can be done to your code, except, it can be shortened slightly like:

makeBooking().then(succesHandler, errorHandler)

succesHandler(response){
    loadDetails(response)
      .then(showDetails, handleDetailsError)
 }

 errorHandler(response){
     if ( checkSoldout(reponse) ){
          makeAlternativeBooking();
     }
 }

Upvotes: 1

Related Questions