Angular 角度4-承诺,一切都不起作用
我正在使用Angular 角度4-承诺,一切都不起作用,angular,rest,promise,Angular,Rest,Promise,我正在使用Promise.all(…)等待一些REST调用结束,然后再使用我需要的服务器数据。代码结构如下所示: const promise1 = this.myService.myFirstRestFunction(a.id).toPromise().then(s => variable1 = s;); const promise2 = this.myService.mySecondRestFunction(b.id).then(r => { this.myService.m
Promise.all(…)
等待一些REST调用结束,然后再使用我需要的服务器数据。代码结构如下所示:
const promise1 = this.myService.myFirstRestFunction(a.id).toPromise().then(s => variable1 = s;);
const promise2 = this.myService.mySecondRestFunction(b.id).then(r => {
this.myService.myThirdRestFunciont(r.id).then(c => variable2 = c);
});
Promise.all([promise1, promise2]).then(p => {
this.myService.getData(variable1.id, variable2.id)
.subscribe(...);
});
但是当我尝试获取id
字段时,variable2
是未定义的。这是否与内部调用的myThirdRestFunction()
有关?如果是这种情况,我如何管理这样的后续REST调用并等待获取最内部的数据?谢谢
编辑:我在@Suren Srapyan和@Sachila Ranawaka回答后更改了代码
const promise1 = this.myService.myFirstRestFunction(a.id).toPromise();
const promise2 = this.myService.mySecondRestFunction(b.id).then(r => {
this.myService.myThirdRestFunciont(r.id);
});
Promise.all([promise1, promise2]).then(p => {
this.myService.getData(p[0].id, p[1].id)
.subscribe(...);
});
在这种情况下,我得到了正确的p[0]
,但是p[1]
仍然没有定义。如果我试图解决第二个承诺,例如:
const promise2 = this.myService.mySecondRestFunction(b.id).then(r => {
this.myService.myThirdRestFunciont(r.id).then(c => console.log(c));
});
对象
c
已正确记录,因此p[1]
不应未定义。不要解析前两个承诺<代码>承诺。所有将为您解决所有承诺
const promise1 = this.myService.myFirstRestFunction(a.id).toPromise()
const promise2 = this.myService.mySecondRestFunction(b.id)
Promise.all([promise1, promise2]).then(p => {
this.myService.getData(variable1.id, variable2.id)
.subscribe(...);
});
您不需要为变量赋值
Promise.all
将尽可能解析所有承诺,并将其结果作为数组传递到p
参数中
只需从函数返回数据,然后通过Promise.all(…)中的p[0]
和p[1]
访问。然后(p=>…)
我不知道你的承诺会有什么回报,所以我提供p[0].id
。根据您的结果更改此选项
要获得更漂亮的代码,还可以析构函数参数
Promise.all([promise1, promise2]).then(([var1, var2]) => {
this.myService.getData(var1.id, var2.id).subscribe(...);
});
Promise.all([promise1, promise2]).then(([var1, var2]) => {
this.myService.getData(var1.id, var2.id).subscribe(...);
});