Can AngularJs $q promises work alongside async/await syntax?

I am currently working on a unique Angular and AngularJs hybrid application with TypeScript versions 9.07, 1.5.11, and 3.7.5. Our HTTP requests are all handled by a wrapper service written in plain Javascript, which was originally designed for the "legacy" AngularJs part of the application. This service generates $q promises using the AngularJs $http service, even for requests made from new Angular components. Since the service is plain JavaScript, there are no typing issues with return values as TypeScript treats them as any, allowing me to cast them as IPromise<TReturnType>.

My main query revolves around whether these promises are fully compatible with TypeScript's async and await keywords. I have tested it with simple examples and it seems to work fine, but I am wary of potential runtime issues that may arise when using those keywords with non-native Promises.

Answer №1

Using the async keyword is perfectly compatible, as it generates a new EcmaScript Promise object without relying on an existing promise instance.

If an async function returns a thenable, the resulting native promise will resolve based on that thenable.

This behavior is demonstrated in the following code snippet:

async function test() {
    let thenable = { then: cb => cb(13) };
    return thenable;
}

let result = test();
console.log(result instanceof Promise);
result.then(console.log); // 13

The await keyword can also be used with a thenable-returning expression, eliminating the need for an EcmaScript-compliant promise:

async function test() {
    let thenable = { then: cb => cb(13) };
    let value = await thenable;
    console.log(value); // 13
}

test();

In summary, both async and await keywords handle thenables appropriately without mandating them to be instances of native Promises.

Additionally, $q promises are indeed thenables, further supporting this behavior.

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

Combining duplicate key-value pairs in a JSON object into an array using JavaScript

Is it possible to merge value objects with the same key but different values? For example, in this case, "field_template_id": 2 appears twice with different values. This is the original JSON data: { "id": "c2dec94f", "data": [ { "field_temp ...

Change a particular value in redux-form using a custom function callback within react-admin

I've made changes to the onDrop function within the ImageInput component to return a custom URL from my own function. My goal is to assign this returned value to the image prop of the ImageInput. ... const uploadImg = ( acceptedFiles ) => { ...

Is there a way to prevent users from right clicking on all links with the same class using js/jquery?

Rails 4 + JS + jquery Is there a way to disable right click on links with the same class in Rails? <% @schedule_hash.values.each do |schedule| %> <%= link_to "Cancellation policy", {:controller => 'web', :action => 'get ...

Redirecting Firebase user authentication to a different webpage

I have developed a signupPage.html to validate a user and save information to the real-time database in Firebase with the following code: signUp_button.addEventListener('click', (e) => { var email = document.getElementById('email ...

Executing a JQuery AJAX request to eliminate a script tag

When using jQuery to call a page via ajax, I encounter an issue with jquery functions loading inside the returned HTML. The problem arises when trying to include a JS file within the returned data, as it seems to strip the script tag: function buildDispla ...

Exploring Ways to Invoke Controller Functions in AngularJS

How can I execute the getinfo() function within the success of the employeecontroller function, which is utilized in the crudApp.controller, to immediately update the table when the submit button is clicked? var crudApp = angular.module('crudApp&apos ...

Disable JavaScript import optimization for a specific file in IntelliJIDEA

I recently came across a tutorial on Angular 2 Google maps that I was following: The tutorial included the following import statement: import { } from 'googlemaps'; However, I encountered a problem where IntelliJ recognized this as an empty im ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

"Implementing a custom dropdown feature using ui-select2 within a directive that is

I am currently nesting a select2 input within a directive and I am trying to bind the selected values to the outer scope. How can I achieve this? Check out this plunker example Here is the code for the directive: app.directive('optionChoices', ...

accomplishing validation in Angular forms while avoiding the use of the HTML form tag

I'm looking to implement Angular Form Validation without the use of an HTML form. I attempted the following code, but unfortunately, the button remains enabled. <ng-form name="login"> <div class="input-group"> <span class="input ...

Ajax modal login feature refuses to close

Struggling to close a modal login box? Everything seems to be functioning correctly with the modal screen and ajax features, but I'm facing issues when it comes to closing the modal form. The code snippet looks like this: HTML: <a href="#" cla ...

What is the process to designate a specific value to a key in an array?

I need assistance in updating the description array within the schema by adding the about and link values, followed by using the .save() function to store it in the database. Any guidance on this issue would be greatly appreciated. Thank you for your help. ...

Restrict the display of items in a unordered list element

Below is my code snippet that limits the number of visible list items in a ul: $wnd.$(el) .find('li:gt(9)') .hide() .end() .append( $wnd.$('<li>+More</li>').click( function(){ $wnd.$(this).nextAl ...

Sidenav Angular Material cdkScrollable is an effective tool for creating scrollable

In Angular Material CDK, there is a special Directive called CdkScrollable that allows you to monitor ScrollEvents within a specific container. I am currently attempting to retrieve the CdkScrollable associated with the default MatSidenavContent. Unfor ...

Can you explain how NGXS store manages its data storage? Is there a memory limit set for the NGXS store? And where exactly is the NGXS store memory located within the browser

Although I attempted to learn NGRX from their official site, I found myself lacking a clear understanding of where and how the data is stored within NGRX. Additionally, I could not find any information regarding the maximum limit of data that can be stor ...

Issues with excessive firing of JQuery blur and hide functions

I am currently using jQuery v1.11.2 and have set up a basic JSFiddle at this link (http://jsfiddle.net/k1g3upbv/). The layout may not be ideal in JSFiddle due to the integration of Twitter Bootstrap within my project. I quickly put together the JSFiddle, o ...

"Upon compilation, the Angular app displays a blank screen instead of the expected

Recently, I attempted to create a client for a web application using Angular. I initiated the process with ng new client, and when I ran it at that point, it displayed the default webpage. Afterwards, I made modifications to the app.component.{html, css ...

Restrict the number of rows displayed in the ui-grid to the maximum

I'm looking to adjust the height of the ui-grid so that it fits the size of 3 rows. After reviewing the ui-grid documentation, I noticed that there is a minRowsToShow property available, but couldn't find an equivalent for maxRowsToShow. I' ...

Unfortunately, the rootScope cannot be accessed within the window.onnotification function

In my code, I am attempting to set up $rootScope as a global variable so that it can be accessed in the controller. Here is an excerpt from app.js: angular.module('app', ['ionic', 'app.controllers', 'app.routes', & ...

Encountering the NullInjectorError when Angular 17 is unable to find a provider for the function(options)

I'm new to Angular (version 17) and encountered an error: ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_LoginPageComponent])[function(options) { -> function(options) { -> function(options) { -> function(options) { -> functio ...