Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting Promise Chain to an external function

So Promises make everything so much cleaner and all but how do I extrapolate the end of a promise chain to an external function?

For example:

SomePromise.then(result => {
    // do stuff here
}).catch(err => {
    // do more stuff here
})

SomePromise2.then(result => {
    // do stuff here
}).catch(err => {
    // do more stuff here
})

SomePromise3.then(result => {
    // do stuff here
}).catch(err => {
    // do more stuff here
})

Somehow, I’d like to extract the then and catch so that I can pass a function into the then like such:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SomePromise.then(handler);
SomePromise2.then(handler);
SomePromise3.then(handler);

I suppose I could extract the entire Promise into a function and pass parameters to and from there but that feels a bit clunky. Any elegant solutions?

Edit: I should elaborate that I’m focusing on the catch part. Imagine multiple different queries with identical data-parsers and error handlers.

Edit 2: In hindsight I realize now that I could just extrapolate

handler = () => {}
errorHandler = () => {}

Promise.then(handler)
       .catch(errorHandler)

but the

>Solution :

let p1=Promise.resolve(1);
function handler(data){console.log(data)};
function errorHandler(error){console.log(error)};
p1.then(handler,errorHandler);

Multiple things here, your code you are expecting is:

SomePromise.then(handler);

However it should be in actual as

function handler(data){};
SomePromise.then((data)=>handler(data));

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading