Last active
October 7, 2016 21:55
-
-
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
This file contains hidden or 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
// 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