The callback function inside the .then block of a Promise.all never gets

I'm currently attempting to utilize Promise.all and map in place of the forEach loop to make the task asynchronous. All promises within the Promise.all array are executed and resolved. Here is the code snippet:

loadDistances() {
    //return new Promise((resolve, reject) => {
      let rrr;
      let arr = [];
      this.geolocation.getCurrentPosition().then((resp) => {            
          // resp.coords.latitude
          rrr = resp;
          console.log(rrr + "              rrrrrrrrrrrrrrrrrrrrrrrrrr");

          setTimeout(() => {
            this.distancelist = this.af.list('/profiles/stylists');

            let x = 0;
            this.subscription6 = this.distancelist.subscribe(items => {

              let mapped = items.map((item) => {
                return new Promise(resolve => {
                  let rr;
                  //console.log(JSON.stringify(item) + "               *((*&*&*&*&^&*&*&*(&*(&*&*(&(&(&*(              :::" + x);
                  if(item.address == "") {
                    /*if(!item.picURL) {
                      item.picURL = 'assets/blankprof.png';
                    }*/
                  }
                  else {
                    console.log(item.address + " is the address empty??????");
                    this.nativeGeocoder.forwardGeocode(item.address)
                      .then((coordinates: NativeGeocoderForwardResult) => {
                        console.log("I AM IN THE GEOCODING ***&&*&*&*&*");
                          rr = this.round(this.distance(coordinates.latitude, coordinates.longitude, rrr.coords.latitude, rrr.coords.longitude, "M"), 1);
                          if(!item.picURL) {
                            item.picURL = 'assets/blankprof.png';
                          }
                          arr.push({'pic':item.picURL, 'salon':item.username, 'distance':rr});
                          console.log("push to the array of results");
                          resolve();
                        }).catch(e => {
                          console.log(e.message + " caught this error");
                          resolve();
                        })
                  }

                })
              });

              let results = Promise.all(mapped);
              results.then(() => {
                console.log(JSON.stringify(arr) + " :FOSIEJO:SFJ::EFIJSEFIJS:EFJS:IO THIS IODIOSJ:FDSIJ :DIS");
                arr.sort(function(a,b) {
                  return a.distance - b.distance;
                });

                this.distances = arr.slice();
              })

            });//);
          }, 1500)




      /*}).catch((error) => {
        this.diagnostic.switchToLocationSettings();
        console.log('Error getting location', error.message);
        resolve();
      });*/

    });


  }

The output on the console displays:

[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
... (repeated messages) ...
[12:38:29]  console.log: push to the array of results 

Despite the alternating messages suggesting success with all promises being resolved, the line

console.log(JSON.stringify(arr) + " :FOSIEJO:SFJ::EFIJSEFIJS:EFJS:IO THIS IODIOSJ:FDSIJ :DIS");
never appears in the console. As a result, the then block of the results from Promise.all is not reached.

Answer №1

Your code contains unresolved paths, for example:

if(item.address == "") {
  /*if(!item.picURL) {
    item.picURL = 'assets/blankprof.png';
  }*/
  //arr.push({'pic':item.picURL, 'salon':item.username, 'distance':"No Address"});
  //x++;
}

Answer №2

Deadlocks can easily occur as @andy-gaskell mentioned when creating new Promises. To prevent this, consider implementing one of the following methods; Any of these may result in an error or return 1.

function promiseWithTryCatch() {
  return new Promise((resolve, reject) => {
    try {
      let result;
      // your code

      resolve(result);
    }
    catch(ex) {
      reject(ex);
    }
  })
}

function promiseWithResolve() {
  return Promise.resolve()
    .then(() => {
      let result;
      // your code

      return result; 
    })
}

async function promiseWithAsync() {
  let result;
  // your code

  return result;
}

Replace the comment with your code and store the final result in the variable "result". If your code involves async operations, it's recommended to create a new function following the same pattern and return that as the result, for example: result = [promise method]

  • The riskiest approach is using "new Promise", as any unresolved or unrejected code will lead to a deadlock. Therefore, make sure to have proper try/catch blocks.
  • If you utilize Promise.resolve(), errors within .then will be captured but avoid placing any code outside .then. In case there are exceptions, catch them and return Promise.reject(new Error())
  • The most secure option is using async functions, where any "throw" statement will result in a Promise.reject, while "return" will lead to a Promise.resolve

Experiment with the given example, although async/await has been commented out due to limitations of this snippet tool not supporting ES2016.

function nestedPromise(num) {
  return Promise.resolve(' myNestedValue is ' + num);
}

function promiseWithTryCatch() {
  return new Promise((resolve, reject) => {
    try {
      let mynumber = 2 + 5;

      nestedPromise(mynumber)
        .then((answer) => {
          resolve(answer.trim());
        })
        .catch(ex => {
          // error handling for async-code
          reject(ex);
        })
    }
    catch(ex) {
      // error handling for sync-code
      reject(ex);
    }
  })
}

function promiseWithResolve() {
  return Promise.resolve()
    .then(() => {
      let mynumber = 2 + 5;

      return nestedPromise(mynumber);
    })
    .then((answer) => {
      // do something with the answer
      return answer.trim();
    })
}

/*
async function promiseWithAsync() {
  let mynumber = 2 + 5;
  let answer = await nestedPromise(mynumber);
  
  return answer.trim();
}
*/

promiseWithTryCatch()
  .then(answer => console.log('promiseWithTryCatch result is ' + answer))
   .catch(err => console.log('promiseWithAsync error is ' + err.message));
   
promiseWithResolve()
  .then(answer => console.log('promiseWithResolve result is ' + answer))
  .catch(err => console.log('promiseWithResolve error is ' + err.message));

/*
promiseWithAsync()
  .then(answer => console.log('promiseWithAsync result is' + answer))
  .catch(err => console.log('promiseWithAsync error is ' + err.message));
*/

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

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

Bootstrap form validation solution

Utilizing bootstrap validation to validate a jsp page. The folder structure is as follows: WebContent ├── bootstrap-form-validation ├── js └── pages All three folders are under the web content. If I create another folder called teacher ...

There seems to be an issue with the next-sitemap image location showing as undefined in the sitemap

I am having an issue with creating a sitemap in image:loc. When I view my xml in the browser, loc is showing as undefined. The goal is to display images present in blogs. Additionally, when I use console.log, the link displays in the terminal but shows as ...

JavaScript: A timer that relies solely on the concept of TIME

Hello all, I have a specific question regarding starting a timer in JavaScript for a test scenario. Despite researching on my own and seeking help on various platforms, I haven't found a solution that fits my requirements. I am looking to implement a ...

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

The ng-controller directive fails to function on the content of Kendo tabstrip tabs

My ng-controller is not functioning properly for the kendo tabstrip tab content. Could you please review my code below? <!--tabstripCtrl.js--> angular.module('tabstripApp',[]); var app = angular.module('tabstripApp'); app.con ...

Whenever I use NextJS's <Link> component, I always end up getting redirected to a

After searching online, I came across this question and tried to implement the suggested solution, but it's still not working for me. Apologies for any duplication. I have a simple link tag that is resulting in a 404 error: <Link className={classe ...

Enhance your website's performance by optimizing Javascript page loading time when using

I've implemented a simple JavaScript function that calculates the loading time of a URL: var beforeLoad = (new Date()).getTime(); $('#myiframe').one('load', function() { var afterLoad = (new Date()).getTime(); var result = ...

Updating the content with HTML and JavaScript

Hello everyone, I am currently working on a project to change the content of a div using JavaScript for educational purposes. Here is what I have done so far - <div id="navbar"> ... <ul> <li> <text onclick="getWordProcessing() ...

Using jQuery and Flask-WTF to achieve live word count in a TextAreaField - a step-by-step guide!

I am interested in adding a real-time word count feature to a TextAreaField using jQuery. I found an example that I plan to use as the basis for my code: <html lang="en"> <head> <script src= "https://code.jquery.com/jquery ...

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

Currently troubleshooting an issue with the CSS that is affecting the table header alignment

At first, I posed this Question and developed my own plugin to accomplish the task. However, I am encountering an unusual CSS issue with the table. Once I applied the plugin, the borders of table cells became disorganized. Here is a jsFiddle showcasing ...

The property 'x' cannot be found on the data type 'true | Point'

I am dealing with a variable named ctx which can be either of type boolean or Point. Here is how Point is defined: type Point = { x: number y: number } In my React component, I have the following setup: const App = () => { const [ctx, toggleC ...

JavaScript Age Calculator - Counting Days

Hey there! I've got an interesting problem. I currently have three text boxes on my webpage, and what I want to achieve is having a fourth text box generated when the user clicks a button. The content of this new text box should be filled with the dat ...

The lack of a defined theme in the makeStyles for @mui/styles sets it apart from @material-ui/core

Struggling to update my material-ui from version 4.11 to version 5 and running into problems with themes. import { createTheme } from '@mui/material/styles'; import { ThemeProvider, StyledEngineProvider, } from '@mui/material/styles&apo ...

Using Three.js to showcase 3 different slices of heatmaps within a 3D environment

I'm working on using Three.js to create a 3D representation of a matrix. Each 2D plane in the matrix should be displayed as a 2D heatmap. Here is an example of what I'm aiming for: https://i.sstatic.net/Kj5yb.png My current obstacle is figuring ...

Converting Buffers to Binary with JavaScript Node.js

I've been working with Node.JS Buffers to send and receive packets, but I'm struggling to figure out how to convert these buffers into binary representation. I attempted the following code snippet, but it didn't yield the expected results co ...

Is there a way to make the primary button on the previous page function correctly again, just like it did before it was clicked?

Issue Description: I am facing an issue on the order page where I need to link the "Continue" button to a booking page. After reaching the booking page, I expect users to be able to navigate between the two pages seamlessly even when they use the browser& ...

Is it possible to implement PortalVue in multiple Vue.js single file components?

While working on Vue.js (single file components), I have discovered three methods of passing data around: local state/props, store, and utilizing PortalVue. Through my experiments with PortalVue, I successfully implemented both portal and portal-target wit ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...