Is it okay for a function to be 'awaited' in TypeScript without causing an error?

Waiting for a function that is not even called is a futile endeavor. Surprisingly, neither a compile time error nor a runtime error is generated in such cases. The perplexing question remains - in what scenarios would one wait for a function to be executed?
In the given code snippet, foo remains dormant and goes unused. One might wonder why TypeScript does not flag this as an error.

async function foo(){
    console.log("foo");
}
async function bar(){
    //correct usage should be:   await foo();
    await foo;
}
bar();


//the resulting es6 code.
function foo() {
    return __awaiter(this, void 0, void 0, function* () {
    });
}
function bar() {
    return __awaiter(this, void 0, void 0, function* () {
        yield foo;
    });
}
bar();

Answer №1

When using await <expression>, the <expression> is expected to be a Promise. If it is not a Promise, then the value will be wrapped into a Promise. For an in-depth look at async-await examples, you can explore the ping example on msdn.blogs.

Formally speaking, it is valid to have await 10; because plain objects or primitive values can be wrapped into Promises. So, await foo; acts as a wrapper for the plain object value foo (remember, functions in Javascript are objects).

Where is this useful?

Consider a scenario where the duration of an operation is uncertain. For instance, in a caching system. If the object is already in memory, there is no need to fetch it asynchronously from the source (such as a database or web). Therefore, it can be resolved synchronously (retrieved from memory). However, the interface should remain consistent. This is where you would use await for a plain object.

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

Investigating the issue: Why is my React Typescript canvas image resizing component producing small, fuzzy images from high-quality, large images

I have developed a small image resizer but am facing an issue with the output images being blurry, especially when working with large images. import React, { useState } from 'react'; interface PropsInterface { placeholder: string; resizeTo: ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

Showing the date object in a react component

As a new programmer, I decided to start with React hooks based on recommendations that it's easier to learn. However, I encountered an issue when trying to display the deliveryDate on the screen. React doesn't seem to accept objects as children, ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using <form [formGroup]="loginForm" (submit)="loginFormSubmit()">. What could be causing this issue? https://i.sstatic.net/3M2a5.jpg login.component.ht ...

What is the validity of using Promise.reject().catch(() => 5) in Typescript?

Can you explain why the TS compiler is not flagging an error for this specific code snippet? Promise.reject().catch(() => 5) Upon inspecting the definition of the handler function within the catch, we come across the following code: interface Promise&l ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Leverage the power of Angular's library dependency injection with the @inject

I am currently working on a project that involves a library. Within one of the classes in this library, I am attempting to provide a service using @optional, @host, and @inject decorators with an injection token. In the parent component, I have the optio ...

Tips for deleting a user from the UI prior to making changes to the database

Is there a way to remove a participant from the client side before updating the actual state when the submit button is clicked? Currently, I am working with react-hook-form and TanstackQuery. My process involves fetching data using Tanstack query, display ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Retrieve the document id along with the corresponding data from a collection

Retrieving data from the collection leads and displaying all documents in an HTML table. Upon clicking, I need to extract the document ID of the clicked item as it serves as the sole primary key. P.S I am able to obtain records of all documents in an arra ...

issue with visibility of Angular Component

After following a straightforward YouTube tutorial for beginners on Angular, I encountered an issue. The tutorial covers how to use components, and even though I understand the concept well, the component simply does not appear no matter what I try. Here i ...

Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database: https://i.sstatic.net/m98EO.jpg I am trying to display a list of preferences that a s ...

When it comes to dealing with signature overload, the behavior of Record and Map may not align

This scenario may seem straightforward, but it's causing confusion. I have a function with an overloaded signature that can accept either a Record or a Map. However, even though I am passing a Map as an argument, TypeScript is treating it as a Record. ...

Location of the bundled Webpack index.html file while running locally on a Nativescript WebView

I am currently working on a hybrid app project that involves both NativeScript and Angular. To integrate the two, I have set up a WebView and consolidated all my Angular project files into a folder within my NativeScript project. As part of this setup, I ...

Customize the position values of the Ngx-bootstrap Tooltip manually

I have incorporated ngx-bootstrap into my Angular 4 application. The component I am using is ngx-bootstrap Tooltip: After importing it, I am implementing it in my component's view like this: <button type="button" class="btn btn-primary" ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

What is the process to activate a function within a component once a service method has been run?

I'm currently working on a chart configuration using amCharts, where an eventListener is registered for the bullets. This event listener then triggers another function in my chart service. My goal is to activate a method in my component as soon as th ...