Promise usage analysis


Promise usage analysis

  • Promise is summarized in one sentence:
  • Promise object is used to represent the final state (completion or failure) of an asynchronous operation and the result value of the asynchronous operation.
  • It is generally instantiated through new
  • Receive a constructor with two function parameters, representing the output of success or failure respectively

    This is a simple application scenario

    function promise1() {
    return new Promise((resolve, reject) => {
        //Asynchronous actions are simulated here. Generally speaking, AJAX requests can be placed, and 'promise1 result' is the returned result after the request is successful
        //Note: promise instances can only be returned through the resolve or reject function and obtained with then() or catch()
        //You can't return directly inside... You can't get the promise return value
        setTimeout(() => resolve('promise1-result'), 1000)

. then (response = > console. Log (response)) / / you can see the result of resolve () printed here
. catch (error = > console.log (error)) / / if the status is rejected or a compilation error occurs, print in this step

*The above syntax uses ES6 syntax
*If you rewrite it with Es5 syntax, the effect is the same on compilers that support both syntax, and ES6 syntax is more concise

function promise1() {
return new Promise(function(resolve, reject){
setTimeout(function() {
}, 1000)

*In comparison, you will find that the syntax of ES6 is really too concise
##Let's explain the promise syntax in detail
* new Promise( function(resolve, reject) {...} /* executor */ );
*Promise instantiates a function with a constructor executor and receives two parameters: resolve and reject
*When the promise constructor executes, it immediately calls the executor function and passes the resolve and reject functions as parameters to the executor
*When the resolve and reject functions are called, change the state of promise to completed or rejected, respectively
*In other words, some asynchronous operations are usually performed inside the executor. Once the asynchronous operation is completed (it may succeed / fail)
*Either call the resolve function to change the promise state to full
*Either call the reject function to change the promise state to rejected
*If an error is thrown in the executor function, even if reject is not called, the state of the promise is changed to rejected

###In the above example scenario, if you want to reflect resolve or reject, we write this

function promise1() {
return new Promise((resolve, reject) => {
var result = ”;
setTimeout(() => {
Var result = ‘async result’ / / here is only simulation data. The real situation is to obtain data asynchronously
if(!result) {
Reject (‘No result ‘) / / if the result is empty, change the status to rejected and return the character’ no result ‘
} else {
Resolve (result) / / if you get the result, change the status to fully and return result
}, 1000)

##Let's talk about promise's method in detail
**Promise.all() .race() .resolve() .reject() .then() .catch() .finally()**
1. Promise.all(iterable)
*This method returns a new promise object, which is often used to process the state collection of multiple promise objects
*This object is triggered successfully only when all promise objects in the Iterable parameter object are successful
*Once any promise object in an Iterable fails, the failure of the promise object will be triggered immediately
*After triggering the success status, the new promise object will take an array containing all promise return values in Iterable as the return value of the successful callback 
*If the failure status is triggered, the error information of the first promise object in Iterable that triggers the failure will be taken as its failure error information
*The following is an example:

const getRandom = () => (Math.random()*1000).toFixed(0);
//Taskid is the task ID that performs the asynchronous operation
const asncyTask = (taskID) => new Promise( (resolve, reject) => {
let timeout = getRandom();// Here, the asynchronous request time is 0 ~ 1000 milliseconds
//Print out which task ID is executing, and there is a concise writing method console.log(taskID=${taskID} start.)
console.log(‘taskID=’ + taskID + ‘—start.’)
//Simulate asynchronous execution
setTimeout(() => {
console.log(taskID=${taskID} finished in time=${timeout}.)
Resolve (taskid) / / successful execution returns the ID of the execution
}, timeout)

Promise.all([asncyTask(1), asncyTask(2), asncyTask(3)])
. then (resultlist = > console. Log (‘resultlist:, resultlist)) / / print the returned result array
.catch(error => console.log(error))
//The execution results of the above example are printed as follows:
taskID=1 finished in time=109.
taskID=2 finished in time=790.
taskID=3 finished in time=840.
resultList: (3) [1, 2, 3]
//You can see that all asynchronous executions are executed one by one according to the incoming array order and return the array results

2. Promise.race(iterable) 
*When any sub promise in the Iterable parameter is successful or failed,
*The parent promise will immediately call the corresponding handle of the parent promise binding with the success value or failure details of the child promise as parameters, and return the promise object
*The above explanation is very abstract and not easy to understand
*In fact, the syntax is the same as that of all (), but the processing logic is different,
*Race () will directly return the result if there is a resolve or reject according to any one of the multiple promise instances passed in, and other instances will no longer execute
*The following is an example:

new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => resolve(2), 600)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 300))
]).then(responseValue => console.log(responseValue))
//After executing this script, you can see that the printed result is 3, because the asynchronous execution in the third promise instance is completed for 300 milliseconds first
//This operation scenario can be used to request multiple different servers to obtain data resources first according to the request speed

3. Promise.resolve(value)
*The state of the returned promise object is full, and the value is passed to the corresponding then () method
*There are examples above, so I won't explain them

4. Promise.reject(reason)
*Return a promise object with the status of rejected, and pass the given failure information to the corresponding processing method (catch())

###The following three are prototype methods
5. Promise.prototype.then(onFulfilled, onRejected)
*Add a successful or rejected callback to the current promise, return a new promise, and resolve with the return value of the callback
*During application, an instance of an implemented promise object is used to reference it, such as promise obj. Then (responsevalue)

6. Promise.prototype.catch(onRejected)
*Add a failed callback to the current promise, return a new promise, and resolve with the return value of the callback
*During application, an instance of an implemented promise object is used to reference it, such as promise obj. Then (responsevalue).catch(reasonError)

7. Promise.prototype.finally(onFinally)
*Add an event processing callback to the current promise object. The callback will be called after the current promise runs
*Whether the current promise status is complete or failed
*For example, promiseobj. Then (responsevalue). Catch (reasonerror). Finally (callback)

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]