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

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...

What should be included in the types field of package.json for TypeScript libraries?

I'm finding it challenging to efficiently develop multiple typescript modules simultaneously with code navigation while ensuring the correct publishing method. What should I include in the "types" field of my package.json? Referring to: Typescriptlan ...

Automatically adjust padding in nested lists with ReactJS and MaterialUI v1

How can I automatically add padding to nested lists that may vary in depth due to recursion? Currently, my output looks like this: https://i.stack.imgur.com/6anY9.png: However, I would like it to look like this instead: https://i.stack.imgur.com/dgSPB. ...

Tips for fetching a response after sending an ajax request using XMLHttpRequest

/* The following **frontend** function is executed to transmit a new post (in JSON) to the Node server */ addPost(postData) { const xhr = new XMLHttpRequest(); xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`); xhr.setRe ...

How can I delay the execution of code until a promise is fulfilled?

I have some code with an event listener that is waiting for a promise (window.ethereum.enable()) to resolve before continuing. How can I ensure that my code pauses until this promise is resolved? window.addEventListener('click', async () => { ...

The issue of transform scale not functioning properly in conjunction with background clip and gradients in CSS

Looking to transform a div with the transform: scale(-1,1) property while using background-clip: text on the text within it. However, this causes the text to disappear. Here's what I've attempted: .reverse { transform: scale(-1, 1); } .gr ...

Observable subscription does not result in updating the value

One of the challenges I'm currently facing in my Angular application is the synchronization of data from a server. To keep track of when the last synchronization took place, I have implemented a function to retrieve this information: fetchLastSyncDate ...

Showing HTML element when the model count is zero - ASP.NET MVC View

My view has a dynamic element that switches between two options depending on the Model.Count property. Check out the code below: @if (Model.Count() == 0) { <div class="well well-lg"><h3>Everyone is present! No absences today :)</h3>& ...

How to anticipate an error being thrown by an observable in RxJS

Within my TypeScript application, there exists a method that produces an rxjs Observable. Under certain conditions, this method may use the throwError function: import { throwError } from 'rxjs'; // ... getSomeData(inputValue): Observable<s ...

Tips on creating animations for elements that are triggered when scrolling and become visible

Is there a way to animate an element when it becomes visible on scroll, rather than at a fixed position on the page? I'm currently using code that triggers the animation based on an absolute scroll position, but I'm looking for a more dynamic sol ...

Adjust google maps to fill the entire vertical space available

I found this helpful resource for integrating Google Maps into my Ionic app. Everything is working smoothly, but I am trying to make the map fill the remaining height below the header. Currently, I can only set a fixed height in pixels like this: .angula ...

Handling multiple Ajax requests while refreshing events in fullcalendar.io

Whenever I try to refetch events from fullcalendar after making an ajax request to insert the event, the ajax request ends up executing multiple times. This results in duplicate or even more entries of the same event in the database. Can someone explain ...

Implementing real-time time updates using php ajax technology

It's fascinating how websites can update the time dynamically without using ajax requests. I currently have a comment system in place. $('#comment').click(function(){ $.post(url,{ comment : $(this).siblings('textarea.#commen ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

Issues with Angular's router outlet link functionality not performing as expected

I am encountering difficulties trying to create a link to a named router outlet in Angular. Let's focus on the most crucial part of the code: app-routing-module.ts: import { NgModule } from '@angular/core'; import { RouterModule, Routes } ...

Efficiently managing repeated records in NodeJS using loops

I am trying to retrieve sales records for specific products from a table in my database based on client ID. This is how I attempted to achieve it: public async getData(clientID: any): Promise<any> { try { return await client .scan( ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

"Utilize JavaScript to extract data from JSON and dynamically generate a

I'm currently facing an issue with reading JSON data and populating it in my HTML table. The function to load the JSON data is not working as expected, although the data typing function is functioning properly. I have shared my complete HTML code alo ...

Type-constrained generic key access for enhanced security

While attempting to create a versatile function that retrieves the value of a boolean property using a type-safe approach, I encountered an issue with the compiler not recognizing the type of my value. type KeyOfType<T, V> = keyof { [P in keyof T a ...

Is there a way to selectively import specific functions from a file in NextJs/React rather than importing the entire file?

Imagine this scenario: we have two files, let's call them File A - export const a = () => {} export const b = () => {} Now, consider importing this into File B - import { a } from 'path' When I tried running npm run analyze, it showe ...