Skip to content

Instantly share code, notes, and snippets.

@geekyorion
Created June 28, 2022 18:59
Show Gist options
  • Save geekyorion/4ca54e1ac291507ac5f8504dcce55275 to your computer and use it in GitHub Desktop.
Save geekyorion/4ca54e1ac291507ac5f8504dcce55275 to your computer and use it in GitHub Desktop.
Promise with callback for success and error functions
const getValue = (value, successFn, errorFn) => {
new Promise((res, rej) => {
if (value > 100) {
res(value * 2);
} else {
rej(value / 2);
}
})
.then(data => {
successFn(data);
})
.catch(errData => {
errorFn(errData);
});
};
const evaluate = () => {
const randomNumber = ~~(Math.random() * 200);
getValue(
randomNumber,
(data) => console.log(data),
(err) => {
throw new Error(`since value (value: ${randomNumber}) is less than 100, we are getting half of it: ${err}`);
},
);
}
evaluate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment