In Vue.js development you’ll encounter asynchronous-call scenarios, but sometimes you need to wait for the async to finish before the next step, which is where func().then() comes in. To use this pattern you need Promise. I’m writing this article because when I searched I found some people wrote it wrong, somewhat misleading others, so I’ll write my own version.
What Is Promise
When I searched before, what others wrote was a bit messy, so I’ll explain in plain language, in one sentence: a Promise object represents the eventual state (fulfilled or rejected) of an asynchronous operation, and the resulting value of that asynchronous operation.
Usage Example
I’ll demonstrate Promise usage with ES6 syntax. The scenario: func1 is an async routine, but we need func2 logic to run only after func1 succeeds. Demo:
function func1() {
return new Promise((resolve, reject) => {
// Note: a Promise instance can only return via the resolve or reject function, obtained with then() or catch()
// You can't directly return ... inside; that way you can't get the Promise's return value
// Here we simulate an async action; generally you can place an Ajax request; 'func1-result' is the result returned on success
setTimeout(() => resolve('func1-result'), 1000)
})
}
// Run func2 logic after func1 succeeds
func1().then(response => {
// func2 runs after func1 succeeds
func2();
}).catch (error => {
// func1 failed, log it
console.log (error)
});
From the example above, you should understand Promise usage:
- A Promise is instantiated with a constructor executor, which takes the two functions resolve and reject as arguments.
- The Promise constructor calls the executor function immediately upon execution, passing the resolve and reject functions as arguments to executor.
- When the resolve and reject functions are called, they change the Promise’s state to fulfilled (completed) or rejected (failed), respectively.
- That is, the executor usually performs some async operation internally; once the async operation finishes (possibly success/failure).
- Either call resolve to change the Promise state to fulfilled, or call reject to change the Promise state to rejected.
- If an error is thrown inside the executor, even without calling reject, the Promise’s state changes to rejected.
