When trying to update a variable within the then() method of a Promise, the variable does not reflect

While the console.log inside the for loop successfully prints project with the correct updated attributes for both role and user within the proposer object, it seems that once outside of the loop, the changes are not retained. At that point, all I see is an empty project. How can I ensure that the modified project data persists beyond the loop?

project: Project = {
    course: '',
    title: '',
    description: '',
    proposer: [{role: '', user: ''}],
    approved: false,
    responsible: [{role: '', user: ''}],
    advisor: [{role: '', user: ''}],
    examiner: [{role: '', user: ''}],
    student: [] 
};


populateSchema() {
    var proposerFound = false;

    for (var key in this.project.proposer) {
      this.employeeService.getEmployee(this.project.proposer[key].user)
                      .then((employee: Employee) => {
                        if (employee != null) {
                          proposerFound = true;
                          this.project.proposer[key].role = 'Employee';
                          this.project.proposer[key].user = employee._id;

                          console.log(this.project); // updated attributes
                        }
      });
}


console.log(this.project); // NOT updated attributes, empty

Answer №1

Performing an update within a promise's then block can sometimes cause timing issues. It is important to ensure that your code executes in the correct sequence for expected results.

Consider this revised approach:

updateSchema() {
    var userFound = false;
    var promises: Promise<void>[] = [];

        for (let key in this.project.users) {
            promises.push(this.userService.getUser(this.project.users[key].id)
            .then((user: User) => {
                if (user != null) {
                    userFound = true;
                    this.project.users[key].role = 'User';
                    this.project.users[key].id = user._id;

                    console.log(this.project); // updated data
                }
            }));
    }

    Promise.all(promises).then(() => {
        console.log(this.project);
    });
}

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

Error encountered with npm version 5.8.0 while trying to create a new project using ng new

I keep encountering this error whenever I try to create a new Angular project. I'm unsure whether it is an npm or angular-cli issue. https://i.sstatic.net/MJ0ek.png node -v v8.11.1 npm -v 5.8.0 ng -v 6.0.0 Everything seemed fine before this occur ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

Identifying Whether Angular ng-repeat is Displaying Output or Not

I am trying to display a "No result" message when the search field does not have any matches. The current filter is working fine, but it does not show the message when there are no results. How can I achieve this? <div class="portfolio-list-wrap" ng-co ...

Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map. My goal is to have the popup display 2 buttons: Start from Here Go to this Location The desired outcome looks like this sketch: ___________________ ...

What's the process for validating i18n dictionaries using TypeScript?

Is there a way to enforce type checking on existing keys within dictionaries in react-i18next? This means that TypeScript will provide warnings at compile time if a key does not exist. For example: Let's say we have the following dictionary: { "f ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...

What strategies can be implemented to effectively share code between these two methods?

Is there a way to consolidate code shared between these two JavaScript methods? async getAllActiveRooms(ctx: ?ContextType): Promise<RoomType[]> { //log getAllActiveRooms return this.i.knex('users_rooms') .transacting(ctx ...

Ways to identify whether the ajax error is due to Access-Control-Allow-Origin restriction or if the file is genuinely absent

My question pertains to customizing error messages for Access-Control-Allow-Origin issues and outdated URLs. I want to display specific messages to the user based on different types of errors that may occur. Currently, my code looks like this: $.ajax( { ...

Efficiently integrating new API objects into an array of existing objects in React using Typescript without any duplicates

I am currently working on a custom hook that calls 16 subreddits at once in order to implement an infinite scroll feature. The goal is to update the array with new data when the URL page parameter changes and then map it. However, I am struggling to do thi ...

What causes the validation behavior of Angular 8's ngValue to differ when compared to other situations?

In my code, I have a select field that looks like this: <select class="form-control" formControlName="gasDistributionUtilityId"> <option [ngValue]="null"> -- Select a name -- </option> &l ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

Error message: "Despite using the 'use client' function in Next.js, a ReferenceError occurs as 'window' is undefined."

What is the reason for the server running this hook when "use client" is included? It does not lead to any application crashes, everything functions with no errors, but an error is logged at the const [windowWidth, setWindowWidth] = useState(window.innerWi ...

Troubleshooting the issue of the Delete Service not functioning properly within Angular

ListStore.ts file export class ListstoreComponent implements OnInit { rawlist; name = ''; id = ''; storeid = ""; store: Store; constructor(private api: APIService, private router: Router, private route: ActivatedRoute, pri ...

No errors are being displayed with the React Hook Form using Zod and Material UI

Presenting my custom ProductInfoForm built using Material UI, react-hook-form with zod validations. However, I am encountering an issue: upon submitting the form, the data is displayed in the console as expected, but when intentionally triggering an error, ...

Fixing the error "Type 'unknown' is not a valid index type"

This issue frequently arises. How can it be resolved? The following code snippet shows the structure: <div class="col-4 col-md-3 col-lg-3" *ngFor="let in_settings of invoice_settings | keyvalue"> ...

Unable to obtain Braintree client token using AngularJS

I've developed a brain-tree payment integration plugin that loads at runtime. I generated the client token in a C# server-side class, but I'm struggling to use it in my Angular controller. Is there a way to access my session variable or something ...

What is the best way to extract data from a JavaScript object received from multer?

Currently, I am facing an issue while trying to utilize multer for handling the upload of a CSV file in Express. The goal is to parse the uploaded file line by line. Although I can successfully retrieve the file as an object stored in req.body, I encounter ...

jQuery Validation Plugin Failing to Recognize Correct Input

Feeling lost and frustrated. I've been using the jQuery Validation plugin in my code. Here's a snippet of my jQuery code: $('#form-login').validate({ onsubmit: true, onfocusout: false, errorClass: 'invalid', w ...