首页 > 解决方案 > Promise 的问题

问题描述

我正在做一个 Ionic 项目,但我对承诺和“.then()”感到有点沮丧,尽管我到处都阅读了很多文档。

情况是我有一个具有功能loadClientsgetWaybills. 第一个获取所有有运单的客户,第二个获取一个具体客户的所有运单。

  loadClients() {
    return new Promise(resolve => {
      this.http.get('http://localhost/waybills?fields=descr1_sped&idUser='+ this.id)
        .map(res => res)
        .subscribe(data => {
          this.data = data.json();
          resolve(this.data);
        });
    });
  }

  // GET WAYBILLS
  getWaybills(client) {
    return new Promise(resolve => {
      this.http.get('http://localhost/waybills/?stato=0&idUser='+ this.id +'&descr1_sped='+ client)
        .map(res => res)
        .subscribe(data => {
          this.data = data.json();
          resolve(this.data);
        });
    });
  }

另一方面,在组件上,welcome.ts我有一个loadWaybills在视图加载时调用并正在执行以下代码的函数,我的想法是获取所有客户端,然后获取每个客户端的相应运单。然后,我将只选择已定义的那些。

问题是,在第二个.then()而不是获取变量数据时,我只是未定义......我已经明白,如果你在里面放一个同步代码.then()可以正确执行并使用“数据”,这是结果承诺。为什么我得到这个未定义?

  loadWaybills() {
    //We first load the clients
    this.waybills.loadClients()
      .then(data => {
        this.waybill = data;
        var preClients = this.waybill;
        this.clients = [];
        //Here we're deleting duplicated clients and getWaybills of them)
        for (let i = 0; i < preClients.length; i++) {
          if (this.clients.indexOf(preClients[i].descr1_sped) == -1) {
            this.waybills.getWaybills(preClients[i].descr1_sped)
            .then(data => {
              **//Here we'll check if the clients has waybills or not**
              this.clientWaybills[i] = data;
              this.clients.push(preClients[i].descr1_sped)
            });
          }
        }
      });
  }

标签: angularjsasynchronousionic-framework

解决方案


很难说,因为我们不知道 API 要返回什么。例如,第一个 GET 中的某个地方可能缺少一个字段,而现在对于第二个,它有时会返回未定义。如果它有时只返回 undefined,一个简单的解决方案是在将值分配给变量之前检查该值是否已定义。

如果它总是以未定义的形式返回并且不应该返回,请尝试调试代码并确保值在第二个 .then 之前存在。


推荐阅读