简体   繁体   English

Promise 解决在需要值时返回未定义

[英]Promise resolve returning undefined when value needed

When the page loads, I want to get the page status and employee that is logged in so that info can be used to pull all the orders based on that given data.当页面加载时,我想获取页面状态和登录的员工,以便可以使用信息来根据给定的数据提取所有订单。 The problem is that regardless of what I seem to do the function: loadLoggedUser() returns the active employee too late.问题是,无论我做什么,function: loadLoggedUser() 都太迟返回活跃员工。 My 'console.log()' functions currently throughout come up with this output on page load:我的“console.log()”功能目前在页面加载时会出现这个 output:

resolve one: undefined 
resolve two: 3 
id when needed: undefined 
data: 1 

Here are the functions within the component, the desired order I am trying to achieve is: loadLoggedUser() then loadSelectedStatus() then once both have completed the if statement can decide which function to fire based on the info collected from the other two functions.这是组件中的功能,我想要实现的所需顺序是:loadLoggedUser() 然后 loadSelectedStatus() 然后一旦两者都完成了 if 语句,就可以根据从其他两个函数收集的信息来决定要触发哪个 function。

export class OrdersComponent implements OnInit {
  activeUser = new Employee();

  constructor( public user: Employee ) {}

  ngOnInit(): void {
    this.initializePageData();
  }

  public initializePageData() {
    var self = this;
    this.loadLoggedUser()
      .then(function(resolve) {
        console.log(`resolve one: ${resolve}`);
        self.loadSelectedStatus()
          .then(function(resolve) {
            console.log(`resolve two: ${resolve}`);
            console.log(self.activeUser.id);
            if (self.selectedViewNumber == 2) {
              self.loadOrdersBySalesperson(self.activeUser.id);
            } else {
              if (self.selectedViewNumber == 3) { 
                self.loadOrdersByStatus(self.selectedStatus, 0);
              } else {
                self.loadOrdersByStatus(self.selectedStatus, self.activeUser.id);
              }
            }
          })
      });
  }

These are the four function definitions for the functions used within initizlizePageData():这些是 initizlizePageData() 中使用的函数的四个 function 定义:

  public async loadLoggedUsername() {
    return new Promise<string>((resolve, reject) => {
      var loggedUsername = this.employeeService.getLoggedUsername();
      resolve(loggedUsername);
    });
  }

  public async loadLoggedUser() {
    var self = this;
    this.loadLoggedUsername().then(function(res) {
      var loggedUsername = res;
      return new Promise<any>((resolve, reject) => {
        self.employeeService.getEmployeeByUsername(loggedUsername).subscribe(data => {
          self.activeUser = data;
          console.log(`data: ${data.id}`);
          resolve(data.id);
        });
      });
    });
  }

  public async loadSelectedStatus() {
    return new Promise<number>((resolve, reject) => {
      this.activatedRoute.queryParams.subscribe(params => {
        this.selectedStatus = params['status'];

        if (!this.selectedStatus) {
          this.selectedStatus = 3; 
        }
        resolve(this.selectedStatus);
      });
    });
  }

  public loadOrdersByStatus(selectedStatus: number, userId: number) {
    this.orderService.getOrdersByStatus(selectedStatus, userId).subscribe(res => {
      this.ordersArray = res;
    });
  }

  public loadOrdersBySalesperson(userId: number) {
    this.orderService.getOrdersBySalesperson(userId).subscribe(res => {
      this.ordersArray = res;
    });
  }
}

Any input or feedback is greatly appreciated.非常感谢任何输入或反馈。

You are missing a return keyword in your loadLoggedUser() function.您的loadLoggedUser() function 中缺少return关键字。

Change the statement更改声明

this.loadLoggedUsername().then(function(res) { ... 

to

return this.loadLoggedUsername().then(function(res) { ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM