Ways to trigger a separate function once the asynchronous task has been finished?

I am currently working on an application using AngularJS and TypeScript. In the constructor, I have a load function that is called like this:

private load(): angular.IPromise<void> {

    const progTokInit: string = 'initial';
    this.$scope.progress.start(progTokInit);

    return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => { 
         //Performing operations for each employeeModel to get the finance type of the person
         resp.employeeRates.forEach(employeeModel => this.getFinanceType(employeeModel));

         this.refreshCostRate(...resp.employeeRates)
          .then(() => // Another Function )
          .then(() => // Yet Another Function )
     })
}

In order to fetch the finance type of a person based on their cost center number, I have implemented the getFinanceType() function as follows:

private getFinanceType (employeeModel:any) {
    this.costService.getFinanceType(employeeModel.person.cost_center.getValue()[0])
        .then((result) => {
          console.log('res ', result);
          employeeModel.financeType = result;
          return result;
        });
}

Since the above function is asynchronous, there may be a delay in retrieving all the relevant data. Therefore, I need to ensure that I wait for the getFinanceType() function to complete before moving on to the next step, which involves calling

this.refreshCostRate(...resp.employeeRates)
.

I attempted to use async/await in the getFinanceType() function:

private async getFinanceType (employeeModel:any) {
    await return this.costService.getFinanceType(employeeModel.person.cost_center.getValue()[0])
        .then((result) => {
          console.log('res ', result);
          employeeModel.financeType = result;
          return result;
        });
}

However, I found that the execution continued even before the data was completed, leading to issues with setting the employeeModel.financeType at the right time.

If anyone has suggestions on how to handle this situation and ensure that the getFinanceType() function finishes its task before proceeding to other functions, I would greatly appreciate your help.

Answer №1

Revise the getFinanceType function so that it will deliver the promise:

adjust getFinanceType (employeeModel:any) {
    var value = employeeModel.person.cost_center.getValue()[0]
    give back this.costService.getFinanceType(value)
      .then((result) => {
        console.log('res ', result);
        employeeModel.financeType = result;
        yield result;
    });
}

Then link from the promises returned:

accomplish load(): angular.IPromise<void> {

    const progTokInit: string = 'initial';
    this.$scope.progress.start(progTokInit);

    return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => { 
         //Executing foreach and transmitting employeeModel
         //  to obtain the finance type of the person
         var promiseArr = resp.employeeRates.map(_ => this.getFinanceType(_));
         promiseArr.push(resp);
         yield $q.all(promiseArr);
      })
      .then(financeTypeArr) {
         var resp = financeTypeArr.pop();   
         offer this.refreshCostRate(...resp.employeeRates)
          .then(() => // Another Function )
          .then(() => // Yet Anothoer Function )
     })
}

Employ $q.all to wait for all the data to come back from the server before proceeding to the next stage.

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 could be the reason for a Python server receiving a JSON message as None?

I'm a beginner in web programming and currently trying to grasp the concept of sending messages between a Python server and a JavaScript client. After stumbling upon a helpful guide at , I learned how to set up a Python server using Flask and send re ...

Guide to creating a dynamic dropdown with Ajax in Codeigniter

It feels like the [insertLongNumber]th time someone has asked this question, and despite my research efforts, I'm unable to find a fitting solution. So here it goes. I'm currently tackling a dynamic dropdown conundrum using PHP and AJAX in CodeI ...

I'm having trouble with my jplayerplaylist remove feature, it's not functioning as expected

I am currently working on creating a mobile-friendly version of my website, and I have noticed that the jplayer functionality closely resembles that of my main site. The playlist is updated based on the page you are viewing, with all songs except the one c ...

Sorting Tables through the Power of Drag and Drop

While utilizing both the Jquery Tablesorter plugin and the Drag and Drop plugin together, everything seems to be functioning correctly. However, when attempting to use the serialize function of the tableDnD, an error message stating "empty string getElemen ...

JavaScript halt pushing when a distinct value is encountered

In this coding challenge, I am attempting to populate a 2D array using a while loop. However, I want the loop to stop pushing values into the array when the first column contains three different unique values. The initial code looks like this: var maxuni ...

Button style not being affected by CSS

I'm having trouble changing the background color of a button in CSS. The CSS link is working perfectly fine, and the button changes color when I attempt to apply Bootstrap or use DOM to change it, but not when I use pure CSS. Here's the code sni ...

Prevent secret select fields from being submitted within a form

In my interface, there are a couple of dropdowns where a user can select the first option and based on that selection, a new dropdown will appear. Currently, when posting the form, all the select dropdown values are included in the post data, even the hid ...

Having received a status code of 200 in Flask WebApp, I am still unable to access the page

Currently in the process of developing a webapp using Flask, I have created the homepage where users are required to input their phone number and password. Once entered, the system will send an OTP to the provided phone number. When clicking the signup bu ...

Adjust the JQuery UI Slider value in real-time as you slide the slider

I am currently using a jQuery slider. When I slide the slider, I test for a specific scenario in the slide function. If the scenario is not met, the slider should revert back to its original position. For instance: Let's say the current slider value ...

Removing Angular scope upon splice operation

Why does my entire list get destroyed when trying to remove an item using splice in JavaScript? HTML: <ul class="nav nav-tabs"> <li ng-repeat="pane in panes" ng-class="{active:pane.selected}"> <a href="" ng-click="select(pane)"> ...

Does the React-bootstrap form restrict typing unless the value is set to this.state.value?

Recently, I delved into the world of react-bootstrap for the first time and decided to utilize their form component based on the guidance provided here: https://react-bootstrap.github.io/components.html#forms As I was constructing my component, the code e ...

Retrieve the function reference of a class (not an instance)

I am working on a code that involves using a function to alter existing functions and return a reference to a new function. I aim to apply this function to specific methods within a class. The current state of my code is as follows: function modifyMethod( ...

Arrange a pair of div containers side by side on the webpage without the need to alter the existing

Is there a way to align these two div side by side? <div class="main_one"> <div class="number_one">Title A</div> </div> <div class="main_two"> <div class="number_two">Title B</div> </div> <div class=" ...

Incorporate jQuery Tabs into every individual function for enhanced functionality

Is it possible to have multiple tab functions on the same page using a script for creating tabs easily? I've tried using an each.function to wrap the tabs, but I haven't been successful. The tab changes simultaneously on all rows. For reference, ...

What is the best way to convert JSON data into a string array and showcase the results?

Recently, I've been exploring the fetch API to retrieve some data. After successfully fetching the data and displaying the response using console log, I now face a challenge in utilizing this information. The API provides me with "result", "id", and " ...

You may encounter an error stating "The requested resource does not have the 'Access-Control-Allow-Origin' header" accompanied by an Uncaught SyntaxError saying "Unexpected identifier."

Exploring an AJAX Call var response = ""; //Making an Ajax call to the database server var target_url = "http://SomeIP/db/*create_table*?token=1234qwer&table_name="+table_name+"&array_of_fields={"+final_fields+"}"; function hit_db(callback) { ...

Using TypeScript will result in errors when attempting to use the Promise object and the Awaited keyword

In this example, I am trying to ensure that the function foo does not accept a Promise as an argument, but any other type should be acceptable. export {} function foo<T>(arg: T extends Promise<unknown> ? never : T) { console.log(arg); } asy ...

Trouble with retrieving dates in ISO format

My collection stores the date of birth field in ISO format, for example: ISODate("1980-01-01T20:20:19.198Z") However, when I use a date time picker on my HTML page, it displays the date like this: 01/01/1980 Unfortunately, when querying for the date of ...

Changing the hidden input value to the data-id of a selected <a> element

I've set up a form with a dropdown menu and subdropdowns, generated using a foreach loop through a @Model. When I click on one of the options, I want the value of my hidden input field to match the data-id of the clicked item. This is what I have in ...

When a webpage reload triggers a 404 error, my website's iframe with the source "videoUrl | sanitize" will display

I am attempting to retrieve a videoUrl from a database and set it to the iframe [attr.src] in order to display a YouTube video. It is imperative that the data originates from the database, as there are limitations preventing us from directly uploading and ...