Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of promises. Functions are being called without returning anything but rather initiating another function.

Outlined below is a simplified decision tree:

    1. Create a booking

      • 1.1 (success) - Retrieve booking details

        • 1.1.1 (success) - Display booking details to the user
        • 1.1.2 (fail) - Present retry option
      • 1.2 (fail) - Check errorCode

        • 1.2.1 if (errorCode === 'soldout')
          • 1.2.1.1 - Attempt alternative booking
          • 1.2.1.1.1 (success) Load booking details
          • 1.2.1.1.1.1 (success) CheckPriceDifference()
          • 1.2.1.1.1.2 (fail) Show soldOutMessage();
      • 1.2.2 if (errorCode != 'soldout') * Display retry button.

The code implementation reflects this logic:

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

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

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

Does this approach effectively manage the complexity of working with nested promises?

Answer №1

At every juncture, your flow takes a different direction, limiting the potential modifications to your code. However, a slight simplification could look something like this:

makeReservation().then(successHandler, errorHandler)

successHandler(response){
    fetchInfo(response)
      .then(displayInfo, handleInfoError)
 }

errorHandler(response){
     if ( verifyAvailability(reponse) ){
          suggestAlternativeBooking();
     }
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the display tag in the select dropdown when using ng-options

Check out this code snippet: <select ng-model="something" ng-options="availThing.description for availThing in availableThings > <option value="">-- please choose an option --</option> </select> I have a question regarding t ...

Displaying information from an array in a view and manipulating it using JavaScript

Having trouble displaying array data in a customized way. Here is how my array structure looks: array:2 [▼ "folder1" => array:5 [▼ 0 => "4.png" 1 => "2.png" 2 => "1.png" 3 => "3.png" 4 => "5.png" ] "folder2" ...

jquery carousel slider dynamically append

I have been tasked with creating a dynamic carousel using jQuery AJAX, and my supervisor recommended that I utilize the .append() method. Below is the HTML code for my carousel: <div id="myCarousel"> </div> <div cla ...

Guide to verifying current data using the jQuery validation library combined with CodeIgniter 4 in the presence of automatic CSRF protection

I am currently working on validating a form using the jQuery validation plugin and CodeIgniter 4. I have enabled CSRF protection that auto generates for each request. Initially, I can successfully validate the form on the first request. However, on subsequ ...

How can you organize an array into rows and columns for easier viewing?

Hopefully everything is clear. I am open to making changes if needed to address any important points. In one of my components, the array items are displayed within cards as shown below: <b-card-group deck class="mb-3"> <b-card border-variant ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

"Change opacity smoothly with the FadeToggle feature for a

I have a question that might seem silly, but I can't quite figure it out. How can I extend the duration of the fade effect? window.switchIn = function() { $('.red').fadeToggle(function(){ $('.blue').fadeToggle(function() { ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...

How can I simulate keyboard events in Angular using a button click?

I've included separate buttons for Ctrl+z and Ctrl+y functionalities. When these buttons are clicked, I want them to perform the respective undo and redo actions programmatically. Below is the code snippet for this functionality. undoText(event:MouseE ...

Step-by-step guide to uploading files using cucumber-js

Is there a way to write a script that can successfully fill out a form and upload a file using cucumber-js, selenium, and protractor? I am encountering an issue where there is no xpath/id available to click on when trying to upload a file. How have you d ...

Is it possible to make an AJAX request even when the server file (such as PHP) is missing?

While working on the Sharetronix script, I encountered something unusual. In the console, I noticed that a network request was being sent to the following address: http://localhost/ajax/postform-submit/ajaxtp:xml/r:0 However, I couldn't locate any f ...

The value sent from the ajax call did not reach the PHP file as expected

Here's the code I'm working with: HTML and Javascript: function getValues(){ var filter; $.ajax({ type: "POST", url: "myphpfile.PHP?action=sek", data: "id=1", async: false, suc ...

Prevent deletion of already uploaded images in Blueimp by disabling the delete button

After using the blueimp upload script to upload files, I noticed that the file information is saved in a data table along with the upload timestamp. However, when I go to edit the form, the files reappear. The simple task I want to achieve is disabling th ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

Using the React key attribute for components without distinct identifiers

When dealing with a situation where users need to provide a list of timeframes, it can be tricky to generate a unique key for each component in React. Simply using the index of the array is not sufficient, as items can be removed from the middle of the lis ...

utilizing window.location.href to direct to a page with javascript capabilities

I am currently developing my own personal website. It is designed to be very light in terms of loading and content. This website relies heavily on the use of jquery, so if a user's browser does not have JavaScript enabled, the site will not function ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

What is the impact of Javascript variable scope in the context of "for...in..." loops?

Imagine you have a code snippet like this: dict = {"key":"elem"} for (var elem in dict){ someFunction(function(){ anotherFunction(dict[elem]); }) } Question: Is elem still considered as the temporary variable created in the for...in... s ...