concept
What's promise? It is a constructor and a solution for asynchronous operation. It is generally used to solve callback hell (nested functions)
Let's look at a set of codes first
// Load picture function loadImg(src) { const p = new Promise( (resolve, reject) => { const img = document.createElement('img'); img.onload = () => { resolve(img); } img.onerror = () => { const err = new Error(`Picture loading failed ${src}`); reject(err); } img.src = src; }) return p; } const url = 'https://class.imooc.com/static/module/marketpage2020/img/banner-icon-level0.png?t=2' loadImg(url).then( img => { console.log(img.width); return img; }).then( img => { console.log(img.height); }).catch(ex => console.error(ex));
what? Can't understand and learn? Then I'll take out the basic knowledge of the code and tell you about it.
Create Promise
First, we should learn to create a promise, and then print the execution results:
let p = new Promise((resolve, reject)=>{}) console.log('p',p);
Execution result: print p. p is a Promise object. There is no problem with this print result. However, a small partner may ask, what is pending?
Three states of Promise
The above console prints < state >: "pending" indicates that the status is not executed, because neither resolve nor reject is executed. We don't know whether the promise is successful or failed at this time. Let's look at the following two situations:
let p2 = new Promise((resolve, reject)=>{ resolve() }) console.log('p2',p2); let p3 = new Promise((resolve, reject)=>{ reject() }) console.log('p3',p3);
We can see from the above code that p2 prints the status of completed and p3 prints the status of rejected. It can be seen that Promise has three execution states: pending, completed and rejected
Then, some students will have questions. What if I want to implement two, let's look at the implementation results:
let p4 = new Promise((resolve, reject)=>{ reject() resolve() }) console.log('p4',p4);
The so-called fish and bear's paw can't have both. This also needs our attention: the state is executed only once, and it won't change once it changes.
then method
In the above code, we can see that we just created a Promise object without calling it. The built-in then method of our Promise object can handle these two states (success state and failure state). Its main syntax format is:
p.then( () => { },//Code in successful execution status () => { }//Execution failed code ).then( () => { }, () => { } )
Let's start with a set of codes:
const p = new Promise((resolve, reject) => { reject('2'); resolve('1'); }); p.then( data => { console.log('suc1', data); return 1; }, data => { console.log('err1', data);//implement return 2; } ).then( data => { console.log('suc2', data);//implement throw new Error('I am error3') }, data => { console.log('err2', data); }).then( data => { console.log('suc3', data); }, data => { console.log('err3', data);//implement } )
Execution steps:
1. First, we create the Promise object and execute the reject statement (the resolve statement is not executed).
2. The instantiated p calls the then method, executes the second callback function, and prints: err1 2
3. Since no new Promise object is returned or an error is thrown, execute the first callback function and print: suc2
4. Throw an error and execute the second callback function
5. Print: error3 error: This is error3
Summary:
1. When pending - > fully, execute the first callback function of then
2. When pending - > rejected, execute the second callback function of then
3. After then is executed, a new Promise object is returned. By default, the first callback function is executed
4. When an error is thrown or a new Promise object is returned, execute the second callback function
Catch method
After learning then method, it is easy to learn catch method. It is essentially a special case of then, which is specially used to deal with the rejected state, similar to then (null, err = > {});
Let's start with a set of codes:
const p = new Promise((resolve, reject) => { reject('2'); resolve('1'); }); p.then( data => { console.log('suc1', data); return 1; }, data => { console.log('err1', data);//implement throw new Error('err2'); } ).catch( err =>{ setTimeout(()=>{ console.log(err);//implement },2000) } )
Execution steps:
1. First, we create Promise object and execute reject statement
2. The instantiated p calls the then method, executes the second callback function, and prints: err1 2
3. Throw a new error and catch it through the catch function
4. Print Error: err2 after two seconds
After mastering it, look back at the first code segment. Do you have a new feeling?
I'll be here today and have dinner!