Creating an async function in TypeScript to retrieve the coordinates of a particular location is a useful way to streamline the

I am looking to retrieve the coordinates of a location as the output of a function. The coordinates are already assigned within a fetch method, with latitudes stored as coordinates.lat and longitudes stored as coordinates.lng.

[Currently, it is returning coordinates lat: 0, lng: 0 as I initially declared. However, I need to update these coordinates with new values after fetching data.]

Answer №1

Utilizing the .then() method allows your code to run asynchronously after the previous code has finished, without blocking. For example:

somethingThatTakesAWhile().then(()=>{console.log("A"})
console.log("B");

The output in this case will be:

B
A

To improve readability and functionality, make your function asynchronous and replace the then syntax with the await keyword as shown below:

async function getLatLng(location) {
  let response = await fetch(...);
  let data = await response.json();
  let coordinates = {lat: data..., lng: data...}
  return coordinates;
}

For a better understanding of promises and asynchronous code, refer to Mozilla's guide.

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

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Tips for extracting information from a TypeScript JSON document

Hey there, I'm currently having trouble understanding how to retrieve data from a JSON file. environment.ts: export const environment = { production: false, urlListBooks: "/assets/list-books.json", urlGetBooks: "/assets/edit- ...

Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request. By enabling logging in TypeORM, I am able to observe the e ...

Error TS2304: The identifier 'Map' cannot be found in version 5.1.0 of Node.js, TypeScript version 1.6.2, and WebStorm 11

While utilizing the filewatchers in my WebStorm 11, I encountered a TS2304 error related to ts-compiler 1.62. The error message reads: TS2304: Cannot find name 'Map' By deactivating the filewatcher and running the command tsc --target es6 app ...

"Looking to personalize marker clusters using ngx-leaflet.markercluster? Let's explore some ways to customize

I am currently struggling to implement custom cluster options in ngx-leaflet. My goal is simply to change all marker clusters to display the word "hello". The demo available at https://github.com/Asymmetrik/ngx-leaflet-markercluster/tree/master/src/demo/a ...

Progress Bar Modules

I am currently working on creating a customizable animated progress bar that can be utilized as follows: <bar [type]="'health'" [percentage]="'80'"></bar> It is functional up to the point where I need to adjust different p ...

Unable to bring in Vue component from NPM module

Hello there, I recently developed my own npm package for a navigation bar and I need to incorporate it into my main codebase. Currently, I am utilizing vue @components but I am struggling with integrating the imported component. If anyone has insight on h ...

Guide to swapping out embedded objects within a TypeScript data structure

I am in need of modifying a TypeScript object by conducting a key search. It is important to note that the key may be repeated within the object, so I must ensure it belongs to the correct branch before making modifications to the corresponding object. To ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

The yarn/npm package manager seems to be utilizing outdated code in an inexplicable way when paired with mocha and typescript

I recently encountered a strange issue that has left me scratching my head. When I manually run my test command, I receive two test results. However, when I execute the same command in a yarn/npm script, only one result is displayed. Has anyone else experi ...

Tips for concealing backend data in Angular2 under the conditions where the name is designated as anonymous and the nested array is empty

I'm dealing with an array of data fetched from the backend and I need to meet the following requirements: If the user's name, "from_user_name", is Anonymus, then the contents must be hidden. Hide the messages if the array is empty. Can someone ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Received corrupted file during blob download in Angular 7

When using Angular 7, I am making an API call by posting the URL file and attempting to download it using the 'saveAs' function from the fileSaver library. The file is successfully downloading, but it appears to be corrupted and cannot be opened. ...

Does the Typescript compiler sometimes skip adding braces?

I am encountering a problem with compiling a specific section of code in my Angular2 project. public reloadRecords() { let step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps; let data = new Array(this.recordsChartSteps ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Saving the current state of a member variable within an Angular 2 class

export class RSDLeadsComponent implements OnInit{ templateModel:RSDLeads = { "excludedRealStateDomains": [{"domain":""}], "leadAllocationConfigNotEditables": [{"attributeName":""}] }; oldResponse:any; constructor(private la ...

Steering clear of the generic Function type in React with TypeScript

Can anyone help me find a guideline that prohibits the use of "Function" as a type? myMethod: Function; I have searched but couldn't locate any information on this. Appreciate any suggestions :) ...

An error was encountered when attempting to define a file that contains both a class and an interface with an expected sem

Seeking guidance on creating a Typescript file with a class and interface: export class Merchant { constructor( public id: string, public name: string, public state_raw: string, public users: string, ) {} }; export interface MerchantL ...