Skip to content

Instantly share code, notes, and snippets.

@cmstead
Last active March 4, 2019 07:15
Show Gist options
  • Save cmstead/71cfc25750c50a21d76ee70ef5c8dfef to your computer and use it in GitHub Desktop.
Save cmstead/71cfc25750c50a21d76ee70ef5c8dfef to your computer and use it in GitHub Desktop.
promiseReturningService
.getUserData()
.then((userData) => {
// this only runs if there is no error getting user data
return userData.userName;
})
.then((userName) => {
// this only runs if there is no error in all previous calls
console.log(userName);
})
.catch((error) => {
// this only runs if there is an error
console.log(error.message);
})
.finally(() => {
console.log('This always runs');
});
function getUserData() {
return {
then: function (onSuccess, onFailure) {
onSuccess(userData);
return this;
},
catch: function (onFailure) {
const promiseError = new Error('An error occurred');
onFailure(promiseError);
return this;
},
finally: function (onComplete) {
onComplete();
return this;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment