javascript - 如何在 Angular9 中使用 Promise.all 进行两次 api 调用?
问题描述
Promise.all
我使用如下方式进行 api 调用:
Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
return new Promise((resolve, reject) => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
this.serviceB.retry(oretry).subscribe(resolve);
});
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
});
上面的代码工作正常。现在我想在成功完成this.serviceB.retry(oretry)
. 第二个 apithis.serviceB.createDbEntry(sentry)
如下sentry
所示:
const sretry: SDInterface = {
hostName,
Id: this.Id.slice(0, this.Id.length),
reason: this.reason
};
而且,我这样做如下
Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
return this.serviceC.status(hostName)
.then(res => {
return new Promise((resolve, reject) => {
const oretry: ORInterface = {
oQid: res.rows[0].qid,
reason: this.reason
};
const sretry: SDInterface = {
hostName,
Id: this.Id.slice(0, this.Id.length),
reason: this.reason
};
this.serviceB.retry(oretry).subscribe(resolve);
this.serviceB.createDbEntry(sentry).subscribe(resolve);
});
});
}))
.then(() => {
this.dialog.close();
})
.catch(err => {
console.log(err);
});
上面的代码给出了一个错误:
error: "SequelizeValidationError: string violation: Id cannot be an array or an object"
看起来它并没有为每个人调用第二个 apiId
解决方案
你可能想看看forkJoin
import { Observable, forkJoin } from 'rxjs';
接着
ngOnInit() {
let one = this.http.get('some/api/1') //some observable;
let two = this.http.get('some/api/2') // another observable;
forkJoin([one, tow]).subscribe(response => {
// results[0] is our one call
// results[1] is our second call
let var1 = response[1];
let var2 = response[0];
}/*, error => { in case error handler } */);
}
推荐阅读
- python - Python删除空键和空键不会影响我的对象
- python - OpenCV 3.4.1 错误 readNetFromTensorflow Can't open .pb in cv::dnn::ReadProtoFromBinaryFile
- wpf - 如何连接 WPF 和 WebAPI
- kubernetes - Kubernetes可以管理硬件设备吗?
- python - 模板不存在错误...在运行 manage.py 时出现 Django 错误
- python - 在 Python 3 中迭代图像的问题
- javascript - 为什么当 readonly=true 时使用 Javascript 分配给 Primefaces inputText 小部件的值不会发送到服务器?
- elasticsearch - 将 AWS Appsync 与 DynamoDB 结合使用,您是否应该通过将相关数据的“冗余副本”存储在同一个表上来建模关系(非规范化)?
- reactjs - 将 Asp.Net Core 的 React + Redux 入门模板中的入口点更改为控制器
- reactjs - 当更改一个特定的状态设置时,是否有必要重述所有其他状态设置?