首页 > 解决方案 > 如何在 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

标签: javascriptnode.jsangularpromiseangular-promise

解决方案


你可能想看看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 } */); 
}

推荐阅读