I'm new to promises and having a bit of trouble grasping how to combine two promises together. I have a function which resolves a promise and does a few tasks:
loginService (context, credentials) {
context.$http.post(LOGIN_URL, credentials, { emulateJSON: true}).then(response => {
this.user.authenticated = true
localStorage.setItem(TOKEN_STORAGE_NAME, response.body[TOKEN_NAME])
}).catch(response => {
context.error = response.body
})
},
And I want to modify the above code so that I can then do something like the following:
login () {
this.submitButtonLoading = true
loginService(this, this.credentials).then(response => {
this.submitButtonLoading = false
// Do something else here.
}).catch(response => {
this.submitButtonLoading = false
// Do something else here.
})
}
What's the proper way to handle this?
Return the promise from loginService
, then you can keep chaining:
loginService (context, credentials) {
return context.$http.post(LOGIN_URL, credentials, { emulateJSON: true})
.then(response => {
this.user.authenticated = true
localStorage.setItem(TOKEN_STORAGE_NAME, response.body[TOKEN_NAME])
})
.catch(response => {
context.error = response.body
})
}
login () {
this.submitButtonLoading = true
loginService(this, this.credentials)
.then(_ => {
this.submitButtonLoading = false
// ...
})
}
Note that the then()
function in login
will always be executed, no matter whether the call succeeds or not.