承诺的麻烦



我正在做一个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)
});
}
}
});
}

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

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

最新更新