Promise
What is promise?

A
Promiseis an object consisting of state, result, callback handlerWhen the status is changed to success/ failed, the callback function will be put into micro-task queue
Why need promise?
As we know, javascript is single-thread. If async function is arranged, the callback will be done at the end of the function, which is not the same as our expectation. Therefore, we need promise to queue up the handler. For example: For the api call, we might want trigger the handler in sequence after the data is got from api end point.
Case 1 :
Ajax method is also a typical example. Let's take axios as an example
Case 2:
Status of Promise
Pending: the promise function is progressing
Fulfilled: the promise function is successful
Rejected: the promise function is failed
Structure of Promise
Then : Promise return successfully
Catch : Failed to return promise, to do error handling
Final : The end of the promise function
Example:
Rewrite by using promise
Case 1:
Case 2: (Actually axios is a function with promise, so we don't need to make a new promise function)
Feature
Callback
The resolve and reject is a callback of the promise, so that it will be triggered at last

Chain
Method
Promise All
Run multiple promise functions at the same time and then return the result
Promise Race
Compare and return the promise that is the fastest to be resolved
Async & Await
Introduction
With long chaining of promise, which may make the code not readable
In order to make code more clean and looks exactly like synchronous code, we can use async await to replace the chaining
Return Value
The return value must be a promise

In sequence vs Concurrent
Last updated
Was this helpful?