在Promise的then()中设置变量时不会更新变量

时间:2017-04-19 13:09:37

标签: javascript angular typescript

for循环中的console.log正确打印projectroleuser属性已更新proposer。但是,当我离开循环时,尝试在底部打印相同的东西时,我更改的属性不会更新,而我获得的所有属性都是空的project。那么如何在循环中“保存”project

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

1 个答案:

答案 0 :(得分:1)

您正在承诺中执行更新。您的最后一个控制台行在当时......

之前执行

这应该有效:

populateSchema() {
    var proposerFound = false;
    var promises: Promise<void>[] = [];

        for (let key in this.project.proposer) {
            promises.push(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
                }
            }));
    }

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