1. What is Promise
Promise is a new solution to asynchronous solution in Es6, which is translated as promise. Before Promise appeared, the data returned by the interface we obtained was returned through the callback function. The consequence of this is that when we later project When it is relatively large, it will cause code blockage, which is difficult to understand, bloated, and difficult to maintain. Slowly it will cause the emergence of callback hell.
The so-called callback hell:
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('得到最终结果: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
Reading callback hell code is a real headache and unacceptable. . . . .
Promises can now be used to solve this problem
doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('得到最终结果: ' + finalResult);
})
.catch(failureCallback);
Through the chain call of Promise, I instantly feel the clarity and understandability of the code
- Promise chain calls reduce the difficulty of code compilation
- Significantly enhanced code readability
Promise has three states
- in progress
- resolve successful callback
- reject callback on failure
features
- The state of the object is not affected by the outside world, only the result of the asynchronous operation can determine which state it is currently in
- Once the state changes (from
pending
change tofulfilled
and frompending
change torejected
), it will not change again, and this result can be obtained at any time
2. Usage
Promise
The object is a constructor that can declare a variable to create an instance
Promise
The constructor accepts a function as a parameter whose two parameters are resolve
andreject
resolve
The role of the function is to changePromise
the status of the object from "incomplete" to "successful"reject
The role of the function is to changePromise
the status of the object from "incomplete" to "failed"
Promise
The constructed instance has the following methods:
- then() //successful callback
- catch() //Failed callback
- finally() //Specify the operation that will be performed regardless of the final state of the Promise object