1. The original intention of promise:
1. Realize asynchronous operation
2. Solve callback hell
Promise is a constructor , which has reject, resolve, and race methods, and then and catch methods on the prototype chain. Using new to create a promise object will have these methods.
1. It is designed as a global constructor
2. The object created by this function is a special data container
3. There are three states inside the data container: Waiting ==> correct data generated Wrong data generated
4. When creating an object, it is required to pass a function parameter ==> that is, to process time-consuming business in this function. General usage:
new Promise((resolve,reject)=>{resolve(),reject()})
2. The then and catch methods in the promise function
Initial state: pending ---> successful state: fulfilled call resolve
Initial state: pending ---> failure state: rejected call reject
promise object.then(function(res){}): Execution succeeded
The res in the callback function in the first then method represents the parameter value of the success or failure (resolve, reject) function
promise object.catch(function(err){}): Execution failed
The res parameter in the then method is the return value of the previous then method
let pro1 = new Promise(function(resolve, reject) {
// resolve 成功
// reject 失败
if (1) {
// resolve("成功啦!");
resolve(2);
} else {
reject("失败啦!");
}
})
pro1.then(res => {
console.log(res);
return "我是第一个then方法的返回值"
})
.then(res => {
console.log(res);
return "我是第二个then方法的返回值"
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
console.log(3);