Skip to content

Instantly share code, notes, and snippets.

@jdtorregrosas
Created April 4, 2019 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdtorregrosas/aeee96dd07558a5d18db1ff02f31e21a to your computer and use it in GitHub Desktop.
Save jdtorregrosas/aeee96dd07558a5d18db1ff02f31e21a to your computer and use it in GitHub Desktop.
Simple promises creation from callbacks API
/* Callbacks function */
const asyncFn = (i, success, error) => {
if (i === 0) return error('Failed!');
setTimeout(() => {
return success('Worked!!');
}, 1000);
};
/* Function call like in old times */
asyncFn(
1,
res => {
console.log('Timed Out Freund!', res);
},
error => {
console.log('Ups', error);
}
);
/* Promesify method */
const promesify = fn => {
return (...params) => ({
then: cbThen => ({
catch: cbCatch => {
fn(...params, cbThen, cbCatch);
}
})
});
};
/* Promesified function */
const asyncFnPromised = promesify(asyncFn);
/* Promesified function call */
asyncFnPromised(0)
.then(res => {
console.log('Timed Out Alter!', res);
})
.catch(error => {
console.log('Timed Out Exploded!', error);
});
@Jacob-Lockwood
Copy link

It isn't actually promisified because you can't chain the promises or use async/await. A similar function would do the trick:

const promisify =
  (fn) =>
  (...params) =>
    new Promise((resolve, reject) => fn(...params, resolve, reject));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment