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

Exploring smooth scrolling functionality using AngularJS and integrating it with IFrames

After implementing an angular controller, I included the following code: angular.element(document).ready(function () { ... } Within this setup, I added a function to enable smooth scrolling to the hash of window.location.hash using .animate({scrollTop... ...

Executing JavaScript Function on the Server Side

Recently, I created a JavaScript function that looks like this: function ShowMsg(msg) { $.blockUI({ message: '<div dir=rtl align=center><h1><p>' + msg + '</p></h1></div>', css: { ...

JavaScript zooming library designed to provide interactive zoom functionality similar to Google Maps

Seeking guidance on creating a web app centered around a zooming principle (ZUI). Currently researching frameworks or starting points, similar to OpenZoom but in javascript. Any recommendations appreciated! ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

Use JavaScript to switch the h1 title when selecting an option from the dropdown menu

As a beginner in coding, I am struggling to find a solution using an if statement for this particular problem. Although I can achieve the desired result with HTML code and options, this time I need to use arrays and an if function. My goal is to create a ...

Guide to manipulating DOM elements with Angular.js: inserting or deleting elements using createElement

Within my Angular directive, I am dynamically generating an external script from the DOM for a specific object within a list. This script includes both a 'script' tag and div content. While I am able to successfully add the script, I am encounter ...

"Utilize Cypress to simulate clicking a button by triggering the enter key

Currently, I'm conducting testing on my application and attempting to trigger a button click using the Enter key: <v-btn class="submit-button" block color="primary" @click="login" > Log In < ...

Having trouble locating the module in my Node.js application

I am encountering an issue with my application, the directory structure is as follows: myApp controllers cars.js models car.js app.js package.json In my code, I reference my model and controller in the following manner... var express = req ...

Divide a string into an array starting from the end

I have a unique phrase. var phrase = "LoremipsumdolorsitametconsectetuadipiscingelitSeddoeiusmodtemporincididuntutlaboreetaliqua"; I am interested in dividing it into chunks of 11 characters starting from the end. Currently, I use: function splitPhrase ...

Is it possible to utilize AngularJS's $q functionality outside of an Angular component?

I am currently working on a browser application, where I have a specific file responsible for creating and initializing an object. This file is written in plain Javascript rather than being part of the Angular ecosystem like the rest of the app, which is b ...

Efficient Mongodb ODM for FastAPI and Python applications

In my fastapi application, I initially used motor as my driver for handling asynchronous db calls. However, as the scale of my project grew, I found the need for proper ODM support in MongoDB. After exploring various available ODM options like beanie and ...

What is the process for assigning a regular expression to an object?

As I work on editing a configuration file, I'm encountering some issues where things aren't quite functioning as expected. Below is the code snippet I am working with: config.module.rules.unshift( { test: "/ckeditor5-[^/\\ ...

The CSS Bootstrap 4 class 'input-group-append' is not functioning properly. Just recently, the styles were displaying correctly

My web application using AngularJS 1.7.8, jQuery 3.3.1, Bootstrap 4.3.1, and various other CSS and JS libraries worked seamlessly last week. However, today I noticed an issue with the button visualization. To Replicate: Visit openskymap.org to see my d ...

Experience a seamless transition to the next section with just one scroll, allowing for a full

I've been attempting to create a smooth scroll effect to move to the next section using Javascript. However, I'm encountering issues with the window's top distance not being calculated correctly. I'm looking to have the full screen div ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

Using React's useState hook with an array of objects

When I have 3 different inputs, my goal is to capture their states while updating the onChange input attribute. The desired state format should be structured as follows: [{lang: (inputName), text: (inputValue)}, ..]. This is what I attempted: function onC ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

Is it possible to gradually open or close a div element?

Looking for a way to add an effect to the code below that opens/closes a div on mouseover above an image. Any examples or suggestions? I'm not exactly a javascript expert. HTML: <div> <div class="under"><img src="http://oi60.tinypic.c ...

ReactJS is unable to locate a valid DOM element within the target container

I recently embarked on my journey to learn ReactJS and I celebrated successfully writing my first code. However, when I encountered the same pattern with components, an error popped up stating _Invariant Violation: registerComponent(...): Target container ...

Form in HTML with Automatic Multiplication Functionality in pure JavaScript

I'm struggling with integrating a simplified HTML form with JavaScript to dynamically adjust and multiply the entered amount by 100 before sending it via the GET method to a specific endpoint. Below is the HTML form: <body> <form method= ...