The basic concept of promise and how to solve the asynchronous programming problem in JS Promis and all Ctch analysis and the understanding of await async

Source: Internet
Author: User

* Promise Commitment* Solve the problem of asynchronous programming in JS** Asynchronous-synchronous* Blocking-no blocking** What is the difference between synchronous and asynchronous? Synchronous refers to the mechanism by which the requested person (the handler of the thing) is notified when it is done. Async: When the event is completed, the requestor sends a message informing the requestor that the transaction is complete. During this time the requestor can choose whether to continue waiting for the command to complete or to do something else to wait for the requested person to return. Synchronization: When the process is completed, the requestor will not inform the requestor, wait until the requestor sends a query to inform the blocking, non-blocking refers to the requestor blocking: for the requester, when the person entrusted to others to deal with some things, the requestor is waiting for the request to process the completion or continue to perform other tasks. Blocking is waiting for things to be done before they continue to do non-blocking: For the requestor, the requester delegates the requester to do something other than the requestor's answer, and asks the requested person every once in a while whether the event is complete. JS uses asynchronous non-blocking mode. Promise is a constructor (when to use promise when we do something that needs to be synchronized) to call promise through new promise:* Constructor function* New Promise (callback)* Callback: The task to be processed asynchronously gets a promise object through the promise constructor, and the callback we pass in will be executed by the Promise object* Promise will maintain a task state, which is a promise internal property* [[Promisestatus]]* This property has a total of three values* 1. Pending: Processing, the Promise object will be changed to that state once it is created, he is the default value* 2. Resolved: Processing complete* 3. Rejected: Processing failed* Resolved,rejected These two states are required to be maintained manually by us. Because the outcome of an asynchronous task is a success or failure, it is determined by our specific business, and the promise object cannot be determined.
We need to change the state of the Promise object according to the actual situation in our business process.* Change Promise Status* When we pass a callback function to the Promise object, the Promise object executes the callback function, and two arguments are passed to the callback, so we can receive both parameters in the callback function* Both of these parameters are a function* Resolve* When we call this function, we change the state of the current promise object to Resolved* Reject* When we call this function, we change the state of the current promise object to rejected**There is one more way to promise objects: then * This method receives two parameters, both of which are callback functions, and these two callback are not executed immediately, and when the promise state changes, it executes the function passed in the then method. A bit like event binding * when the promise state becomes resolved, then the first argument to execute then callback * When the promise state becomes rejected, then the second parameter of then is callback: now we have a delay timer settimeout as follows var a=10; SetTimeout (() =>{a+=10;},1000); console. log (a); //at this time a print out for 10 because in JS for asynchronous non-blocking language in the delay timer function has not been executed, the following console.log has been executed so print out as 10. Then we want to be able to do this after the delay timer processing value. var a=10; var p1=new Promise ((resolve,reject) =>{setTimeout (() =>{a+=10; Resolve (err) //processing completed},1000); //the function in then is executed only when the processing is complete. Then the object in Resolve () is then the argument. }) P1.then (() =>{console. Log (a)}); The print is now.
Column 2 Promise
Then how does the method pass the data * We can pass the data through the Resolve,reject method * We just need to call the above two functions to pass to the subsequentThen the data of the method as its parameters can be *Catch is similarThe catch method is to capture the promiseAnd then passed the promise so many nested words to takeThen the way to listen is too cumbersomeThe catch listener has a primary execution error that will beCatch captures thereby executingfunction in Catch * */New Promise ((Resolve, reject) = {Let b =10; SetTimeout (() = {b + =10; Resolve (b);Reject' The first task went wrong '); },1000); }).Then (function (b) {Console.log (b);ReturnNew Promise ((Resolve, reject) = {SetTimeout ( () = {b *= 2; resolve (b); //reject ( "the second task went wrong"), 1000); }); }). then (function (b) {console.log (b); return new Promise ( (resolve, reject) = {SetTimeout ( () = {b *= b; Resolve (b); Reject (1000); }); }). then (function (b) {console.log (b);}). catch (function (err) {console.log (err);});     
The all method of promise
new Promise((resolve, reject) => {        let a = 1;        setTimeout(() => { a++;

Reject (' one '); Resolve (a); }, Math.random () * 1000); });

VarP2 = new Promise ((Resolve, reject) and {letb =2; SetTimeout (() = {b++; resolve (b);}, Math.random () * +) ;}) ; / * * Wrap two different asynchronous tasks in a Promise object, and then call the Promise object static method all to pass the above multiple asynchronous promise as an array to the parameters of the all method * This time the Promise.all method maintains a state, which is determined by the state of the multiple asynchronous tasks that are passed in * when the state of multiple asynchronous tasks becomes resolved, then all state is resolved, But as soon as the state of an asynchronous task becomes rejected, the state of all becomes rejected * */ p1 P2 is two promise in the following method only if p1 p2 is resolved, the following function method Promise.all ([p1, p2]) is executed . then ([A, b] = = {Console.log (A, b);}). catch (Err) = {Console.log (err);})              
Promise another way to await async
await async 是es7 定义的新标准        通过 async 声明一个异步函数在该函数中         async function(){ await fn1 //这个fn1 代表一个函数 await fn2//这样的话在fn1 执行完成之后才会执行fn2 }

The basic concept of promise and how to solve the asynchronous programming problem in JS Promis and all Ctch analysis and the understanding of await async

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.