- ES6 grammar
- Promise is a solution to asynchronous programming
- new Promise((resolve, reject) => {…… })
When do you use Promise
Typically, when there is an asynchronous operation, use Promise to encapsulate the asynchronous operation
// The Promise argument is a function, here (resolve, reject) => {} // This function takes two arguments: resolve,reject, and reject // chain programming new Promise((resolve, reject) => { // Asynchronous operation setTimeout((data) => { // Judge success or failure here // Call resolve on success, then.then() if(){ resolve(data); } else { // Call reject on failure reject('error.. ')}},1000) }).then((data) => { // Where the business is actually done console.log("hello world"); }).catch(err => { console.log(err); }) Copy the code
Three states of Promise
- Pending: Pending state, such as network request in progress or timer out of time
- Fulfill: fulfill state (fulfill state) Fulfill state (fulfill state) Fulfill state (fulfill state)
- Reject: Reject state, which is in when we actively call back, and is called back. Catch ()
The chain call to Promise
In.then() there is no asynchronous operation, but the data from the previous step needs to be processed. For logical layering, chain layering is possible
One of two ways
- Using Promise. Resovle (newdata) :
return Promise.resolve(data + '2222')
- Return newdata:
return data+'111'
/ / a layer .then((data) => { console.log(data); // The next layer of res comes from here return Promise.resolve(data + '2222') //return data+'2222' }).then(res => { console.log(res); }) Copy the code
In. Then, no asynchronous operation is performed, but the err of the previous step needs to be processed. For logical layering, chain layering can be performed
One of two ways
- Using Promise. Reject (err) :
return Promise.reject(err + '2222')
- Throw err: ‘throw data+’111’
.then(res => { console.log(res); return Promise.reject(res + '+err1') //throw res + '111' }).catch(err => { console.log(err); }) Copy the code
Promise.all()
Promise.all([ Promise1, Promise2 ]).then(res => { / / Promise1 results res[0]... / / Promise2 results res[1]... }) Copy the code