Janier
Janier

Reputation: 4402

how to convert promise.all to observables

I have this particular code which sends a file to an api using promises.. the api accepts one file at a time and i have multiple files..so i used a promise array and promise.all sample code as below

            const docPromises = new Array<Promise<ResponseType>>();
            for (const doc of docs) {
                docPromises.push(this.sendDoc(doc));            
            return Promise.all(docPromises).then(
                (responses: ResponseType[]) => {                  
                    return resolve();
                },
                (error: Response | any) => {                  
                    return reject(error);
                }
            )
                .catch((error: Response | any) => {                
                    return reject(error);
                });

in the this.sendDoc, i am doing this.http.post

How can i change this to rxjs? i looked up a bit..but nothing i can find for promises.all

Upvotes: 0

Views: 1434

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12950

In rxjs forkJoin is the alternative for Promise.all

someFunction() {
    const docPromises = new Array<Promise<ResponseType>>();
    for (const doc of docs) {
        docPromises.push(this.sendDoc(doc));
    }
    return forkJoin(...docPromises).map(
        (responseAsArr) => {
            // do something here if you want to, manipulate the response,
            // (if not then no need of map)
            return responseAsArr
        }
    ).catch((exception) => {                
        return throwError(exception);
    });
}

// call It like:

context.somefunction().sunscribe((data) => {
    // success
},(err) => {
    // err
}, () => {
    // complete
})

Upvotes: 2

Related Questions