Ensure that the function has finished executing before proceeding in Typescript

I need help with a function that calculates the route between two points.

 public FindClosestPoint(waypoint,currentLocation){
     let distances = [];
     for(var i=0; i< waypoint.length;i++){
         debugger

         var rWP1 = new L.Routing.Waypoint;
         rWP1.latLng = currentLocation;    

         var rWP2 = new L.Routing.Waypoint;
         rWP2.latLng = waypoint[i];   

         var myRoute =L.Routing.mapbox('access-token');
         myRoute.route([rWP1, rWP2], function(err, routes) {
             debugger
             var distance = routes[0].summary.totalDistance;
             distances.push(distance);
         });
     }  
     var minDistance=Math.min.apply(Math, distances)
     console.log("distances "+distances);
 }

However, I'm encountering an issue where the myRoute.route() function is executing after the FindClosestPoint() function, causing me to not retrieve the distance accurately. I am looking for a way to make myRoute.route() execute inside the for-loop and move on to the next iteration smoothly.

Is there a solution to achieve this? If so, how can it be done? Or are there other alternatives available?

Answer №1

It's a good idea to encapsulate this function within a Promise object.

function get_routes(rWP1, rWP2) {
    return new Promise((resolve, reject) => {
        myRoute.route([rWP1, rWP2], function (err, routes) {
            if (err) {
                reject(err);
            } else {
                resolve(routes)
            }
        });
    })
}

You can then utilize the await keyword inside an async function or create an array of promise objects and use Promise.all.

Answer №2

To clarify, it is important to note that any function in javascript containing a callback will not execute synchronously. Therefore, the async keyword must be used when handling such functions.

async.eachSeries(waypoint, function(item, nextitem) {
    async.waterfall([
         function(callback) {
             var rWP1 = new L.Routing.Waypoint;
             rWP1.latLng = currentLocation;    
             var rWP2 = new L.Routing.Waypoint;
             rWP2.latLng = item;
             callback(null, [rWP1, rWP2]);
         },
         function(data, callback) {
             myRoute.route([rWP1, rWP2], function(err, routes) {
                  var distance = routes[0].summary.totalDistance;
                  distances.push(distance);
                  if(distances.length === waypoint.length){
                      var minDistance=Math.min.apply(Math, distances)
                      console.log("distances "+distances);
                  } else {
                      callback(null, 3); //3 is just a random value you can give
                  } 
             });
         }
    ],nextitem)         
});

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

Retrieve a specific attribute from an HTTP Observable result

Calling all RxJS experts, I have a question for you. Currently working with Angular 5. Here's what I am trying to accomplish: this.allFilters = this.http.get(path).pipe( map((response) => response.forms.sim_filter.schema.properties)) The ...

The font awesome symbol is not showing up in the nz-th element

I've encountered an issue with the code snippet below: <th [ngSwitch]="sortIcon" nz-th class="centered" (click)="toggleSortOrder()" nzSort="Stopped">Sort <i *ngSwitchCase="sortEnum.NoSort" class="fa fa-lg fa-fw fa-sort"></i> ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

Transform type definitions declared using CommonJS to type definitions that do not rely on a module system

Currently in the process of transitioning from VS 2013 with TS 1.8 to VS 2017 with TS 2.5. As part of this update, it appears that I need to upgrade typings for react and other dependencies. Unfortunately, the new typings are utilizing commonjs : https: ...

The integration of react-color Saturation with @types/react-color is currently unavailable

In my quest to develop a customized color picker, I am utilizing the react-color library (^2.19.3) together with @types/react-color (^3.0.4). The issue arises when trying to import the Saturation component since it is not exported from the types in the ind ...

Suggestions for keys in TypeScript objects

I am looking to create a TypeScript type that will suggest certain object keys in the editor, while still allowing users to define arbitrary keys if they wish. Here is the type I have defined: type SuggestedProperties = 'click' | 'change&apo ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

Tips for switching Echarts theme colors

Currently, I have integrated the echarts library into my angular 8 application. Below is the customized theme object that I am utilizing: let customTheme = { version: 1, themeName: "customed", theme: { seriesCnt: 3, ...

A new object type is being introduced that allows for a dynamic number of keys and values. It also supports values that can be either a

I'm working on a project using NextJS and TypeScript. I have a function named submitFunc that needs to accept three arguments - type (string), base endpoint (string), and an object with dynamic keys and values, where the values can be either strings o ...

If the Angular checkbox is selected, update the value of another input

I am looking for a way to change the value of an input field in another div to disabled when a checkbox is checked. `` <div class="24hr-example"> <input placeholder="24hr format" aria-label="24hr format" [ngxTimepicker]="fullTime" [forma ...

What is the best method for creating a zod schema for an intricately nested object?

Here is the data I am working with: { "2022-06-01": { "09:00am": { "time_table_id": 1, "job_id": 4, "start_working_time": "09:00am", "end_working_time": &qu ...

How do you implement a conditional radio button in Angular 2?

I am facing an issue with two radio buttons functionality. When the first radio button is selected and the user clicks a button, the display should be set to false. On the other hand, when the second radio button is chosen and the button is clicked, ' ...

Modifying the Design of Angular Material Dialog

I am currently working on creating a modal using Angular Material Dialog, but I want to customize the style of Angular Material with Bootstrap modal style. I have tried using 'panelClass' but the style is not being applied. Has anyone else faced ...

Do the material cards in Angular 7 resemble the layout of Pinterest?

How can I achieve a Pinterest-like layout for Angular Material cards? Here is my current code: <div fxFlex fxLayout="column" fxLayoutGap="10px" style="height: 100vh"> <div fxLayout="row wrap"> <!-- loop over the cardList and show the ...

Limiting input values in Angular 8 number fields

I am working on an Angular 8 application and I want to restrict the user from entering any value outside the range of 0-100 in a number input field. My initial idea was to implement something like this: <input type="number" [ngModel]="value" (ngModelC ...

Is there a way to avoid using the super() constructor unnecessarily in Eslint?

code: constructor(cdr: ChangeDetectorRef, inj: Injector) { super(cdr, inj); } eslint: { ... overrides: { ... rules: { ... "@typescript-eslint/no-useless-constructor": "error", ... ...

Add hover effects to components inside MuiButton

I'm currently working with styled components and Material UI, but I'm struggling to add hover styles to the children of MuiButton. Despite following online resources and documentation, I can't seem to make it work. Here's how my jsx is ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...