Created
April 4, 2019 21:50
-
-
Save jdtorregrosas/aeee96dd07558a5d18db1ff02f31e21a to your computer and use it in GitHub Desktop.
Simple promises creation from callbacks API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It isn't actually promisified because you can't chain the promises or use
async/await
. A similar function would do the trick: