angularjs - Promise 的问题
问题描述
我正在做一个 Ionic 项目,但我对承诺和“.then()”感到有点沮丧,尽管我到处都阅读了很多文档。
情况是我有一个具有功能loadClients
和getWaybills
. 第一个获取所有有运单的客户,第二个获取一个具体客户的所有运单。
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 中的某个地方可能缺少一个字段,而现在对于第二个,它有时会返回未定义。如果它有时只返回 undefined,一个简单的解决方案是在将值分配给变量之前检查该值是否已定义。
如果它总是以未定义的形式返回并且不应该返回,请尝试调试代码并确保值在第二个 .then 之前存在。
推荐阅读
- iphone - 发布使用 animate cc 创建的应用程序失败
- java - org.jgroups 中的 Wildfly 18 NoSuchMethodError
- html - 如何使用 Wasm 和 Rust 服务多个 HTML 页面?
- react-native - 将 payUbiz 与 react-native 集成
- magento2 - Magento 2 管理页面内容
- java - 在 Spring Boot 中将 servlet 请求注入到控制器
- php - 我可以在 AWS API 的哪个位置设置发送短信的发件人 ID
- multithreading - 条件变量真的需要另一个变量吗?
- python - 在 python 中运行 Parallel 时导致“Killed”错误的原因是什么?
- php - 在 MySQL 中使用持久连接但仍有许多打开的连接