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:
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));