简体   繁体   中英

How to convert a Subsink api call to Promise.all within Angular9?

I have the following async function which uses Subsink

import {SubSink} from 'subsink';
...
...
async retryClick() {
        for (let i = 0; i < this.Id.length; i++) {
            const res = await this.serviceC.status(this.hostName[i]);
            const qId =  res.rows[0].qid;
            const oretry: ORInterface = {
                oQId: qId,
                reason: this.reason
            };
            this.subs.sink = this.serviceB.retry(oretry)
                .subscribe(s => {
                    if (i === this.serverId.length - 1) {
                        this.dialog.close();
                    }
                });
        }
    }

I want to write the above code using Promise.all

Promise.all(this.hostName.slice(0, this.Id.length).map(hostName =>
            this.serviceC.status(hostName)
                .then(res => console.log(res.rows[0].qid))
        )).then(() => this.dialog.close());
    

The above code is working fine using Promise.all
Here Id is of type any

How to add oretry: ORInterface and remaining statements in the above Promise.all ?

With a bit of guesswork (and assuming that this.hostName.slice(0, this.Id.length).map(...) is correct) it appears that you are trying to do this ...

Promise.all(this.hostName.slice(0, this.Id.length).map((hostName) => {
    return this.serviceC.status(hostName)
    .then(res => {
        // Here `this.serviceB.retry(oretry).subscribe` must be promisified, 
        // in order to keep the promise chain, thence `Promise.all()` informed.
        return new Promise((resolve, reject) => { 
            const oretry: ORInterface = {
                'oQId': res.rows[0].qid,
                'reason': this.reason
            };
            this.serviceB.retry(oretry).subscribe(resolve); // No need to test if (i === this.serverId.length - 1). 
                                                            // The last .subscribe(resolve) to fire will trigger this.dialog.close() below
        });
    });
}))
.then(() => {
    this.dialog.close();
})
.catch(err => {
    console.log(err);
    this.dialog.close(); // presumably
});

... but note that the last .subscribe(resolve) to fire will not necessarily correspond with the final this.serviceC.status(hostName) call. The Promises returned by .map() will (in all liklihood) settle in any order; that's the nature of asynchronism. This may or may not matter to your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM