Skip to content

Instantly share code, notes, and snippets.

@Kosmin
Last active October 7, 2016 21:55
Show Gist options
  • Save Kosmin/4af3d281bde209f695675238a6931b24 to your computer and use it in GitHub Desktop.
Save Kosmin/4af3d281bde209f695675238a6931b24 to your computer and use it in GitHub Desktop.
Wrap any function in a promise to use `.then` regardless of whether that function returns a promise
// Simple interface used to execute a callback in different ways depending on
// whether or not a function returns a promise or not.
// Usage:
// import Promisable from 'promisable';
//
// Promisable(someFunction()).then(() => {
// promiseWasSuccessful()
// }, promiseFailed());
//
//
export default function (initialResult) {
return new Promise((resolve, reject) => {
// If we're dealing with a promise
if (typeof initialResult !== 'undefined' && typeof initialResult.then === 'function') {
initialResult.then((data) => {
resolve(data);
}, (error) => {
reject(error);
});
// If the initialResult is just a regular variable, not a promise
} else {
resolve(initialResult);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment