At the beginning, what meaning do not understand, I hope to be able to understand more thoroughly.

JS asynchronous programming model

What is synchronization

If you can get the results directly is synchronous, such as you in the hospital registration, get the number will leave the window. The synchronization task may take 10ms or 3 seconds;

What is asynchrony

If you can’t get the results directly like if you’re waiting for a table in front of a restaurant, you get the number to go shopping. When can we eat?

How do I determine if a function is synchronous or asynchronous

If a function returns a value within three things: setTimeout AJAX, AddEventListener, then that function is an asynchronous function asynchronous and Promise what is synchronization? What is asynchrony? synchronous

You can get the results directly. For example, when you go to the hospital for registration, you will leave the window after you get the number. The synchronization task may consume 10ms or 3s, but you will not leave until you get the results.

Function f1() {console.log(” hello “); } function f2() { console.log(“hello”); } f1(); f2(); The copy code above is synchronous code, and f2 must wait for f1 to finish executing.

asynchronous

If you can’t get the results directly, like if you’re waiting for a table in front of a restaurant, you get the number to go shopping.

When can we eat?

You can ask at the restaurant every ten minutes.

You can also use wechat to receive notifications (callbacks)

For example:

Function f1() {setTimeout(() => {console.log(” hello “); }, 3000); } function f2() { console.log(“hello”); } f1(); f2(); At this point, the code will execute F2 directly and wait at least 3s before executing function f1. In fact, f1 will be put into the event queue after waiting for 3 seconds. At this point, f1 function in the event queue will be executed only when the main thread is idle.

Js in the most basic asynchronous implementation is to call setTimeout,setInterval

The function you write to yourself is not a callback

The function you write for someone else is a callback

Such as the request. The onreadystatechange is addressed to browser calls

Here’s an example:

function add(num1, num2, callback){ var sum = num1 + num2; callback(sum); }

function print(num){ console.log(num); }

add(1, 2, print); Print is a callback

The relationship between asynchrony and callback

Asynchronous tasks need to notify JS to get the results when they get them

Make js leave a function address to the browser

The browser calls this function address when the asynchronous task is complete

It also passes the result as an argument to the function

This is a callback function that I wrote for the browser to call

The difference between

Asynchronous tasks require callback functions to notify the result

However, callbacks are not only used for asynchronous tasks, they can also be used for synchronous tasks

array.forEach(n=>console.log(n))

Determine synchronous or asynchronous

A function is asynchronous if its return value is inside setTimeout, Ajax (XMLHttpRequest), and AddEventListener.

Promise What if an asynchronous task has two outcomes: success and failure?

There are two methods:

1. The callback takes two arguments

Fs. ReadFile (‘. The / 1. TXT ‘, (error, data) = > {the if (error) {the console. The log (‘ failure ‘); Return} console.log(data.tostring ()) // success}) duplicates code 2. Make two callbacks

Ajax (‘ get ‘, ‘/ 1. Json, data = > {}, the error = > {}) / / in front is a success callback, followed by failure callback ajax (‘ get’, ‘/ 1. Json, {success: () = > {}, fail: ()=>{}}) // Accept an object with two keys, indicating success and failure of copying code but there is a problem with either method one or method two:

1. The code is not standard and the name is multifarious

2. Prone to callback hell

3. Error handling is difficult

How to solve the callback problem?

This led to the promise design pattern

Its usage:

return new Promise((resolve,reject)=>{… Reject (error) resolve and reject(error) resolve and reject(error) Then (success,fail) passed in the success and failure function copy code Promise introduction

Promise is not a front-end invention.Promise is currently a unified solution to asynchronous problems in the front-end. Use return new Promise((resolve, reject)=> {}) to construct a Promise that contains a.then() function property

Resolve is a call to success, reject is a call to fail. then(succes, fail)

The.then() method returns an instance of Promise. It contains at most two arguments: a callback function Promise for success and failure cases.

Use the.then method

var p1 = new Promise((resolve, reject) => { resolve(‘Success! ‘); // or // reject(new Error(“Error!” )); });

p1.then(value => { console.log(value); // Success! }, reason => { console.error(reason); // Error! }); In the above code, resolve(…) is called if the execution succeeds. Reject (…) is called when asynchronous code fails. The function argument in.then is the above call to resolve(…). The value passed by the method.

getJSON(“/posts.json”).then(function(json) { return json.post; }).then(function(post) { // proceed }); The code above uses the THEN method to specify two callback functions in turn. After the first callback completes, the second callback is passed the result as an argument. If the previous callback returns a Promise object, the later callback waits for the Promise object to run before calling it.

.catch

Used to specify the callback function when an error occurs.

Then (function(posts) {// some code}).catch(function(error) {// Handle the error that happened when the previous callback was running Console. log(‘ Error! ‘, error); }); Errors that copy code Promise objects have the “bubbling” nature of passing them backwards until they are caught. That is, an error is always caught by the next catch statement.

getJSON(“/post/1.json”).then(function(post) { return getJSON(post.commentURL); }). Then (function(comments) {// some code}). Catch (function(error) {// Copy the code promise.all ()

Promise.all(promiseArray) is a static method on a Promise object that wraps multiple instances of the Promise object to generate and return a new Promise instance.

Parameter: promiseArray, an array of Promise instances

var p1 = Promise.resolve(1), p2 = Promise.resolve(2), p3 = Promise.resolve(3); Promise.all([p1, p2, p3]).then(function (results) { console.log(results); // [1, 2, 3]}); The method returns only when all promise instances in the PROMISE array become resolve and passes all results to the Results array. Any promise in the promise array is reject, the entire promise. all call terminates immediately and returns a reject new Promise object. The following is an example of reject:

var p1 = Promise.resolve(1), p2 = Promise.reject(2), p3 = Promise.resolve(3); Promise.all([p1, p2, p3]). Then (function (results) {// Then method will not be executed console.log(results); }). Catch (function (e){// The catch method is executed, and the output is: 2 console.log(e); }); Duplicate the code promise.race ()

Promse.race, as the name suggests, means a race, which means that a Promise. Race ([P1, P2, P3]) returns the fastest result, regardless of whether the result itself is a success or a failure.

let p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(‘success’) },1000) })

let p2 = new Promise((resolve, reject) => { setTimeout(() => { reject(‘failed’) }, 500) })

Promise.race([p1, Then ((result) => {console.log(result)}). Catch ((error) => {console.log(error) // open ‘failed’})