ES6(Promise)

Promises (a solution for asynchronous programming)

1. What is asynchronous

Function A, A executes a step, A executes and then executes B. There are two ways to implement this execution method:

  1. Callback 2. Event trigger. Promise is different from these two ways

2. The role of Promises

Troubleshoot asynchronous operations

3. Basic usage of Promises

see code

 

1. Callbacks in ES5 (it will be difficult to solve when the problem is complex, and difficult to maintain later)

(Ajax process)

(Execute "execute" first, and execute timeout1 after 1 second)

 ES6 (Promise) writing

First execute "execute 2", then execute "timeout1", and finally execute "promise timeout2"

 ajax returns the Promise case, executes the next step, that is, the function body of then, resolves executes, and reject stops

 then means next step

 2. Serial process (if there is an error in the middle, how to catch the error)

 

No error, continue to execute downward, so output 6

 

catch is used to catch errors, there are errors, errors are caught

3. Advanced usage of Promise

1. Promise.all (3 images are loaded and displayed together)

 1. Add a picture

2. Display pictures

3. Traverse pictures

Promise.all treats multiple Promise cases as one Promise case, when all three pictures are triggered, the Promise.all object will be triggered, and the then method will be called

4. Results

It will only be displayed when the loading is complete

2. (Only one of the 3 pictures is loaded, first come first served)

1. Add a picture

2. Display pictures

3. Traverse pictures

In multiple states, one instance changes first, and the instance of Promise.race also changes, and the others cannot respond.

4. Results

Show only one

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325173279&siteId=291194637
Recommended