Having trouble with a JavaScript Promise that seems to be stuck in limbo

I have developed two custom promises that are quite similar, with the only difference being that they operate on distinct user inputs. Both promises utilize various classes and methods from Google Maps API v-3.

What's puzzling is that when the first promise is invoked, it consistently returns a reject status without ever resolving. Additionally, even though it doesn't resolve, the code within the promise continues to run, displaying multiple console.log() statements I've added for monitoring purposes.

Here are the two promises:

var checkingDeparture = new Promise((resolve, reject) => {
    console.log('1. checkingDeparture called');  
    var newDeparture = '';
    var geocoder = new google.maps.Geocoder();
        
    geocoder.geocode({'address': $('#startTransfer').val()}, (results, status) => {
        console.log('2. checkingDeparture geocoder called');   
        if(status == google.maps.GeocoderStatus.OK) {
            coordPoint = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                
            if(google.maps.geometry.poly.containsLocation(coordPoint, window.venicePolygon)) {
                console.log('3. checkingDeparture containsLocation called');   
                newDeparture = 'Piazzale Roma, Venezia, VE, Italia';
            }
            else {
                newDeparture = $('#startTransfer').val();
            }
        }
            
        console.log(newDeparture);   
        resolve(newDeparture);
    });
        
    reject('Sorry there was an error with checkingDeparture promise...');
});
    
var checkingDestination = new Promise((resolve, reject) => {
    console.log('1. checkingDestination called');   
    var newDestination = '';
    var geocoder = new google.maps.Geocoder();
        
    geocoder.geocode({'address': $('#endTransfer').val()}, (results, status) => {
        console.log('2. checkingDestination geocoder called');  
        if(status == google.maps.GeocoderStatus.OK) {
            coordPoint = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                
            if(google.maps.geometry.poly.containsLocation(coordPoint, window.venicePolygon)) {
                console.log('3. checkingDestination containsLocation called');   
                newDestination = 'Piazzale Roma, Venezia, VE, Italia';
            }
            else {
                newDestination = $('#endTransfer').val();
            }
        }
            
        console.log(newDestination);   
        resolve(newDestination);
    });
        
    reject('Sorry there was an error with checkingDestination promise...');
});

The following snippet illustrates how these promises are utilized:

var checkedDeparture = checkingDeparture;
var checkedDestination = checkingDestination;
    
Promise.all([checkedDeparture, checkedDestination]).then(() => {
    console.log(checkedDeparture + checkedDestination); 
    var request = {
        origin: checkedDeparture,
        destination: checkedDestination,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC
    };
        
    directionsService.route(request, (result, status) => {
        console.log('4. checking value of origin: ' + request.origin);   
        console.log('5. checking value of destination:' + request.destination);   
        console.log('6. directionsService called');   
        if(status == google.maps.DirectionsStatus.OK) {
            //do things
        }
            
        else {
            directionsDisplay.setDirections({routes: []});
            theMap.setCenter(window.globalCenter);
        }
    });
}).catch(e => {
    console.log(e);
});

Despite extensive testing, I'm unable to pinpoint the source of the issue, particularly since checkingDestination appears to be resolving correctly. As checkingDeparture always rejects (but still executes), any subsequent code chained with .then() won't get executed.

Answer №1

Your commitments are nullified before they come to fruition!

Commitments are designed to be fulfilled only once, whether it's a fulfillment or a refusal, and only the initial one is acknowledged. If you create code like this:

new Commitment((fulfill, refuse) => {
  setTimeout(() => fulfill(), 1000)
  refuse() // this takes precedence
})

it will always end in refusal instead of fulfillment.

This pattern needs to be altered so that refusals only occur when something goes wrong (or after a timeout):

var checkingDeparture = new Commitment((fulfill, refuse) => {
    // snip
        
    geocoder.geocode({'address': $('#startTransfer').val()}, (results, status) => {
        // snip
        if (status === "error") { // Replace this with an actual condition check
          refuse('Apologies, there was an issue with the checkingDeparture commitment...');
        } else {
           fulfill(newDeparture);
        }
    });
        
    
});

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

Tips for locating the index of the previously selected active class

I am currently working on a slider and have made progress up to this point. However, I am facing an issue where I cannot proceed because I need to identify the index of the item from which I removed the last active class before the click event occurs. My ...

The issue arises when attempting to use input alongside debounce, event.persist(), and storing the value at the parent component

Is there a way to implement an input field with debounced search where the value is passed from the parent component? Currently, when I pass the value from the parent component it doesn't work as expected. What would be the correct approach to make th ...

React Button Axios: A Primer for Complete Beginners

For the past few weeks, I've been using create-react-app and trying to modify the App.js file to include a button that executes an axios HTTP request when clicked. However, during my attempts, I keep running into errors like "unexpected token" in hand ...

Using PHP to validate a read-only textbox

I am trying to implement validation on a Datepicker that is set to readonly, but I am facing issues with my current code. Can someone please assist me? Below is the JavaScript code used for error trapping: <script type="text/javascript"> $(func ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

I'm looking to efficiently convert JSON or GeoJSON data into a Backbone model and then seamlessly transition that model into a Leaflet layer. Can anyone provide guidance on

As I work on refining layer definitions that can be added individually to a collection, my goal is to smoothly render the view or add them to a L.LayerGroup using the leaflet api. However, being new to JavaScript, I am uncertain about how to map the proper ...

Customize Button Colors in Bootstrap 4

I'm encountering difficulties when attempting to change the color of the buttons labeled "Print," "Excel," and "PDF". Despite referring to a guide, I wasn't able to succeed. The provided test case differs from my code but shares the same CSS and ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

Animate CSS during page load

Currently, I am implementing AJAX to dynamically load pages on my website. During the loading process, I wish to incorporate a spinning animation on the logo to indicate that content is being fetched. The jQuery script (although I'm still learning an ...

Guide on displaying the value of an element in a Vue modal

I am working with a list of items displayed as <li> elements in a loop. When one of these elements is clicked, I would like a modal box to open up displaying specific content related to that particular element. The following data represents the item ...

Creating code that adheres to the ECMAScript 5 standards

In my quest to create a JavaScript library that adheres to modern standards such as HTML5, CSS3, and ESv5, I find myself wanting to break away from the mainstream libraries like jQuery and MooTools. While these are great tools, I believe in the importance ...

I could use some assistance with deciphering JSON data

After using console.log to display the data I received, I observed an object structured as follows (I trimmed some details for clarity and used ... to indicate repetitive information): [ Submission { title: 'Untitled', content: { ur ...

Update the variable in a PHP script and execute the function once more without the need to refresh the page

Hey there, I'm wondering if AJAX is necessary for the functionality I want to implement. Here's the scenario: I have a function that generates a calendar and I plan to add 'forward' and 'backward' arrows so users can navigate ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Using prerender.io in conjunction with native Node.js

Currently, I am working on integrating prerender.io into my Angular 1.6.0 application that is being hosted on a Node.js server. The instructions provided in the documentation for setting up the middleware involve using the connect middleware, with a speci ...

JavaScript Function to Redirect Page After a Delay of X Seconds

I'm trying to implement a redirect to a specific URL after displaying an error message for 5 seconds. Initially, I used JavaScript like this: document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000)); However, the redirectio ...

Guide to using VueJS for sending a POST request with a JSON array containing data and uploading a File or Picture for each element in the array

I am currently facing a challenge with Axios where I need to send formData from a dynamic Form to PHP. Users should be able to add multiple "persons" along with their respective data and pictures. Below is the format of the data: data: { person:{ ...

Deactivate user input in Knockout Kendo TimePicker

Is it possible to prevent user input in the Kendo UI TimePicker while using knockout-kendo binding? In a previous project without knockout-kendo, I was able to achieve this by using the following code (see jsfiddle example): $('#timepicker').at ...

Express get requests are failing to handle query strings

Whenever I try to extract the year and month from the URL like this: http://localhost:3000/api/posts/2018/4, the code doesn't seem to work properly. Instead, it returns an error saying: Cannot GET /api/posts/2018/4 Here's the JavaScript code I&a ...