Transforming JavaScript/Angular 1 from using Promise.all to async-await technique

Within the $onInit() function, I set two web service calls to run concurrently and store their responses in variables named referencesPromise and contactTypesPromise. If necessary, a new method can be created for this purpose.

$onInit() {
  const referencesPromise = this.ReferenceService.getMultipleReferences(this.AgentReferences)
  const contactTypesPromise = this.ContactService.getContactTypes()
  Promise.all([referencesPromise, contactTypesPromise]).then((responses) => {
    this.references = responses[0]
    this.contactTypes = responses[1]
    const stateParams = this.$state.params
    return this.setContactSteps()
  })
}

In what way could async-await provide an alternative solution for this?

Answer №1

In order to maintain concurrent execution of your methods, there are only a few adjustments that need to be made:

async $onInit() {
  const itemsPromise = this.ItemService.getMultipleItems(this.AgentItems);
  const categoryPromise = this.CategoryService.getCategories();

  this.items = await itemsPromise;
  this.categories = await categoryPromise;
  const stateParams = this.$state.params;
  return this.updateItemStatus();
}

It's important to notice that the initial method calls remain unchanged, as we still want to store the promises to ensure that both requests happen simultaneously.

Answer №2

When using the async/await syntax, there is no direct equivalent to Promise.all. It still operates on promises and is essentially just syntactic sugar for multiple then calls.

Therefore, you can implement it like this:

async $onInit() {
  const referencesPromise = this.ReferenceService.getMultipleReferences(this.AgentReferences)
  const contactTypesPromise = this.ContactService.getContactTypes()
  const responses = await Promise.all([referencesPromise, contactTypesPromise])
  this.references = responses[0]
  this.contactTypes = responses[1]
  const stateParams = this.$state.params
  return this.setContactSteps()
}

(It's worth noting that this approach differs slightly from your original code which did not include a return statement in the $onInit function. Just remember that an async function always returns a promise.)

Answer №3

To achieve the desired outcome in a different way, you can utilize $q.all(). The following example demonstrates how it can be implemented:

$q.all([this.ReferenceService.getMultipleReferences(this.AgentReferences), this.ContactService.getContactTypes()]).then(function(result) {
    this.referencesPromise = result[0];
    this.contactTypesPromise = result[1];
    this.stateParams = this.$state.params;
    return this.setContactSteps();
});

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

Following an ajax request, the tooltip feature in bootstrap fails to function properly

I am currently facing an issue with my files. I have an index.php file where I include another file named file1.php (which consists of all the necessary files for jQuery, js, etc.). Within file1.php, there is a table with buttons that trigger modals. The i ...

Troubleshooting Firefox's inability to properly utilize jQuery's scrollTop() function on the 'body' element

I'm puzzled as to why the scrollTop() jquery function isn't functioning properly on the 'body' element in Firefox. $('body').scrollTop(0); To resolve this issue, I ended up using: $(window).scrollTop(0); The jquery documen ...

Refreshing the page using AJAX in WooCommerce after executing my custom script

I am experiencing an issue with WooCommerce. I am trying to incorporate a custom jQuery script that executes after clicking the add to cart button. When I do not include my script, everything functions properly - the AJAX request triggers and the product i ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Struggling to click on a dynamic link before it times out

Can someone help me with a puzzling issue I can't seem to solve? I am trying to achieve the following: Whenever a link is clicked (for example: mysite.com/blog/blog-article.html), I want to save the href of that link to a variable. Then, in JavaScri ...

An ongoing problem in ThreeJS involves the resizing of images that are not in a power of 2

My issue involves the automatic resizing of textures by WebGLRenderer in threejs. I understand that WebGL requires textures to have dimensions that are powers of 2. In my case, the texture has a wrap set as RepeatWrapping and a size of 65536 x 512, which ...

Regain access to your account by resetting your password through the use of text messaging with Ionic

My current project involves working on the front end of a mobile app using Ionic and Angular, while utilizing an existing API and backend system. One of the key features I need to implement is the ability for customers to reset their password by receiving ...

Tips for organizing JSON data in AngularJS are as follows:

Can someone assist me in looping this array value into 3 columns using angularjs? Currently, my view appears as an HTML table with 3 columns, but the values are displayed vertically instead of horizontally. You can see an example of how it looks here. Bel ...

Importing textures and loading mtl files in Three.js from various web addresses

Something strange is happening with my Roblox API integration. I'm trying to retrieve the OBJ file, MTL file, and Texture file using the API. The main API link I have is https://t2.rbxcdn.com/ef63c826300347dde39b499e56bc874b, which leads me to two cru ...

Obtain a specific element in Puppeteer JS by utilizing the waitForSelector function to detect when its class name changes

I am faced with a situation where I need to wait for a specific element to change its classes dynamically. The challenge arises when utilizing the waitForSelector function, as it fails to work when no new element is added to the DOM. Instead, it is the &l ...

Could JSON be improved for better space efficiency, or is this the standard format?

Within my code, I am using var team = <?php echo json_encode(get_results("SELECT id,name,title,bio,sord,picfn FROM mems ORDER BY sord")); ?>; This code generates a JavaScript array of objects like: var team = [{"id":"1","name":"somename1","title": ...

Is it possible to hide a div using Media Queries until the screen size becomes small enough?

Whenever the screen size shrinks, my navbar sections start getting closer together until they eventually disappear. I've implemented a button for a dropdown menu to replace the navbar links, but I can't seem to make it visible only on screens wit ...

How to send emails in the background using a React Native app

I'm looking to incorporate email functionality into a React Native app so that it can send messages automatically when certain actions occur in the background. ...

Ways to identify if a resize event was caused by the soft keyboard in a mobile browser

Many have debated the soft keyboard, but I am still searching for a suitable solution to my issue. I currently have a resize function like: $(window).resize(function() { ///do stuff }); My goal is to execute the 'stuff' in that function on ...

Tips on choosing the initial option in an Angular JS dropdown menu as the default selection

When trying to utilize a dropdown menu, I am encountering an issue where the 1st value cannot be selected by default and appears blank. The master_data.sch_files data set contains 4 items, but the dropdown displays 5, with the first one being blank. < ...

ClickAwayListener doesn't function correctly when used in conjunction with Collapse or Fade animations

Currently, I am working on implementing a notifications area on my website. The idea is to display a notification icon, and once the user clicks on it, a list of notifications will be shown. For reference, you can view the code in this codesandbox I have ...

Adding a character sequence to a parsed JSON object results in a literal string outcome

I have saved some currency information in the state manager of my app and here is how I am accessing it: For example, to retrieve the value of Euro against the dollar, I use the following code: JSON.parse(this.$store.state.clientSide.currencyrates).rates. ...

What should you do when you need to send a message from a website to an MQTT broker that lacks Websockets support?

Currently venturing into the realm of web development, I find myself tackling a project that involves sending messages from my website to Thingstream, an MQTT broker. My initial attempt using the MQTT Paho JavaScript library was thwarted by the fact that ...

Navigating to JSON input in Express correctly

I have successfully created a basic Express-based API to serve JSON data, but now I want to enhance its functionality. The JSON file follows this structure: (some sections are excluded) [{ "ID": "1", "NAME": "George Washington", "PAGE": "http://en.w ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...