Rafael de Castro
Rafael de Castro

Reputation: 1098

Promise on service returning treated data for another promise on component

I wonder if its possible to do like below, or even how should I can do it. For those who ask why, its because I can guarantee in my service that the returned data will be treated and adjusted as myfile need..

Can you help? XD

Scenary 01 == What I have ==

myFile.ts

methodReturnPromise()
    .then( data => { /* Sucess, Do This */} )
    .catch( err => { /* Failure, Do This Instead */} );

Scenary 02 == What I want ==

service.ts

myServiceMethod(): Promise<any> {
    methodReturnPromise()
        .then( data => { /* Sucess, Treat and return */} )
        .catch( err => { /* Failure, Do This Instead and return */} );
}

myFile.ts

this.myService.myServiceMethod()
    .then( data => { /* Success, Do this */})
    .catch( err => { /* Failure, Do This Instead */} );

Upvotes: 0

Views: 33

Answers (1)

lmarqs
lmarqs

Reputation: 1471

You can use then and catch multiple times. So change the myServiceMethod() for something like this:

myServiceMethod(): Promise<any> {
    return methodReturnPromise()
        .then( data => { 
            /* Success, do something here and return the same data received */ 
            return data; 
         } )
        .catch( err => { 
            /* Failure, do something here and rethrow the same error */

            throw err;
        } );
}

var promise1 = new Promise(function(resolve, reject) {
  resolve("ok");
});

promise1.then(function(data) {
    console.log("log1", data);
    return data;
  })
  .then(function(data) {
    console.log("log2", data);
  });

var promise2 = new Promise(function(resolve, reject) {
  reject("ERROR");
});

promise2.catch(function(err) {
    console.error("error1", err);
    throw err;
  })
  .catch(function(err) {
    console.error("error2", err);
  });

Upvotes: 1

Related Questions