A guide on harnessing the power of a promise in Typescript

Although I am familiar with async/await/then, I recently stumbled upon something new that sparked my curiosity:

Consider the following function:

HelloWorld():Promise<string>
  {
    return new Promise(resolve => {
      setTimeout(() => {
        alert("IN");
        resolve('Hello World!');
      }, 2000);
    });
  }

Now, if I call this function from another function like this:

async onClick()
{
    var p:Promise<string> = this.HelloWorld();

    await(p);

    alert(p);
}

I will see alerts in the order below (after a 2-second delay):

'IN'

'[object Promise]'

My question is, by the time the second alert is triggered, the promise has already been resolved (due to the await(p) call), so its value is set ('Hello World!').

Is there any way to access this value without resorting to the typical .then approach?

For example:

var p:Promise<string> = this.HelloWorld();

await(p);

alert(<VALUE OF PROMISE HERE (which now equals 'Hello World!')>);

As I mentioned earlier, it's simply an experiment and some food for thought.

Answer №1

In this scenario, it's important to note that await is not a function but a keyword. Therefore, the approach you are taking may need some adjustment.

Once a promise is resolved, you have the option to access its resolved value either through the callback of the then method or by directly assigning the value when using await.

For example,

myPromise().then((value) => console.log(value));

Is similar to:

const value = await myPromise();
console.log(value);

In your specific case, you can simply do:

const value = await p;

Or even:

const value = await this.HelloWorld();

It's worth mentioning that there's no necessity to explicitly specify the type of the value since the return type of HelloWorld is already Promise<string>.

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

Angular 2 and .NET Core 2.0 triggering an endless loop upon page refresh detection

My application, built with dotnet core 2.0 and angular 2, allows me to view member details. The process begins with a list page displaying all the members from a SQL Server database. Each member on the list has a link that leads to an individual details pa ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Challenges encountered while compiling Node.js code with ts-node (Error: Cannot use import statement outside a module)

Trying to compile TypeScript code with NodeJS using this command: npx ts-node src/server.ts An error is thrown: SyntaxError: Cannot use import statement outside a module Following the error's instructions: Warning: To load an ES module, set " ...

The latest release of Angular2, rc1, eliminates all parameters that are not in

In the previous beta version, I was able to analyze using split Location.path(), but now it seems to have been removed. How can I prevent this removal? Interestingly, everything works well with matrix parameters (;id=123;token=asd). This was tested on a ...

When using TypeScript in React, the event handler for the onLoad event of an image element cannot locate the properties naturalWidth and naturalHeight

https://i.sstatic.net/vPfkL.png return <img {...props} onLoad={event => { console.log(event.target.naturalWidth) }}/> I am encountering an issue trying to access naturalWidth and naturalHeight in TypeScript React. Unfortunately, TypeScript is ...

Flatten a specific property of an object recursively

If I have a data structure containing nested objects, I need to create a type that removes specific keys and flattens certain fields recursively Input: { sys: { id: string; }; metadata: { author: string; }; fields: { ...

Struggling to configure Sass with @snowpack/app-template-react-typescript

I'm struggling to integrate Sass with the @snowpack/app-template-react-typescript template. I attempted to follow the steps outlined in this guide, but so far I haven't been successful. I even created a new project and tried adding it, but not ...

fetching all objects in one asynchronous request

Seeking assistance with this code on codesandbox. Can someone help? I am looking to display all the feeds from three different sites (stored in FEEDS) on a homepage without needing to click and navigate to a specific slug page. The issue I am facing is f ...

Modify the color of the chosen value on the sidebar using Angular 6

I am looking to update the color of the selected value in the sidebar. Sample <div class="card c-setting"> <div class="card-header" title="Data Uploader"(click)="clickDataloader()"> <a class="card-link" data-toggle="collapse" href="# ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

A method for transferring information stored in chrome.storage to a variable within an Angular component

How can I effectively assign data fetched from chrome.storage.sync.get to my Angular component's variable? Below is the code snippet of my component: export class KTableComponent implements OnInit { words: string[] = []; constructor() { } ...

An easy guide to displaying an HTML string in a DIV with Angular 6

I have a Angular 6 application that interacts with the python API. The API responds with HTML data that I want to display on my existing page within a specific div element. I have attempted various methods but have not been successful. Test.ts public myT ...

Having issues with an Angular reactive form that includes a custom form-level validator and the 'blur' updateOn option?

Having issues combining the following: angular reactive form custom validator at form level (cross-field validator) usage of the 'updateOn' option set to 'blur' A demonstration of the problem can be found in this simple stackblitz: h ...

What are some strategies for troubleshooting asynchronous errors in JavaScript function calls?

I'm currently working on an asynchronous JavaScript code that utilizes the async method findDevices from the class Devices, which is located in a separate file. This method involves performing a mongo find operation within the IDevices collection. Her ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Creating an array by extracting form values in Angular

In my component, I have the following function: updateInfo(info: NgForm) { const changedValues = Object.keys(info.controls) .filter(key => info.controls[key].dirty === true) .map(key => { return { control: key, value: info.co ...

The class constructor in the TSdx package must be invoked with the 'new' keyword

I recently developed a npm package using TSdx to create a small Jest reporter. However, when I try to use this package in another project, an error occurs. Uncaught TypeError: Class constructor BaseReporter cannot be invoked without 'new' at ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Exploring nested promises in TypeScript and Angular 2

I have a method called fallbackToLocalDBfileOrLocalStorageDB, which returns a promise and calls another method named getDBfileXHR, also returning a promise. In the code snippet provided, I am unsure whether I need to use 'resolve()' explicitly o ...

What is the best way to incorporate additional data into a TypeScript object that is structured as JSON?

I'm exploring ways to add more elements to an object, but I'm uncertain about the process. My attempts to push data into the object have been unsuccessful. people = [{ name: 'robert', year: 1993 }]; //I aim to achieve this peopl ...