1. What do you mean by promise?

To solve the problem of falling back to hell, the Promise object is used to represent the final completion (or failure) of an asynchronous operation and its resulting value blog.csdn.net/qq_42698326…

2. Write the output of the specified code?

const first = () =>{ new Promise((resolve,reject)=>{ console.log(3); let p = new Promise((resolve,reject)=>{ console.log(7); setTimeout(()=>{ console.log(5); resolve(6); }, 0); resolve(1); }); resolve(2); p.then(arg =>{ console.log(arg); }); }) } first().then(arg =>{ console.log(arg); }) console.log(4);Copy the code

1. Synchronous code (highest) 3, 7, 4 2. Asynchronous code (second highest, then) 1, 2, 3 Asynchronous code for macro tasks (minimum, setTimeout) 5

Note:

  • Why isn’t there a 6? Only one resolve call can be made within a Promise, so if 1 is called first, 6 will not be called.
  • Multiple promises, how to determine which Promise resolve corresponds to? Nearby principle

3. Practical application of promise?

const openDoor= cb =>{
    setTimeout(cb,1000)
}
Copy the code

Wrap the top as a promise function

const promise = () =>{ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(); })}}, 1000)Copy the code

Chain calls

Const openDoor= () => new Promise(resolve)=>{setTimeout(resolve,1000); } const putIn= () => new Promise(resolve)=>{setTimeout(resolve,1000*3); } const closeDoor= () => new Promise(resolve)=>{setTimeout(resolve,1000); } const done= () => new Promise(resolve)=>{ console.timeEnd(); console.log('done2); resolve(); } openDoor().then(putIn).then(closeDoor).then(done);Copy the code

4. Make a promise yourself?

const Resolve = "resolved"; const Reject = "rejected"; const Pending = "pending"; Const handlePromise = (result, newPromise, resolve, reject) = > {the if (result = = = newPromise) {/ / if the return value is a newPromise is no sense to throw new Error("can not return oneself"); } if((typeof result === "object" && typeof result ! = = null) | | typeof result = = = "function") {/ / figure out whether the returned a promise let lock = false; try{ const then = result.then; If (typeof then === "function"){then.call(result,(r)=>{if(typeof then === "function"){then.call(result,(r)=>{// If (newPromise) is returned Resolve and reject the return; } handlePromise(r,newPromise,resolve,reject); // When PROMISE returns {name:'123',then:123} lock=true; },(e)=>{ if(lock){ return; } reject(e); lock=true; }) }else{ resolve(result); } }catch(error){ reject(error) } }else{ resolve(result); }}; class JJPromise{ status = Pending; result = undefined; reason = undefined; onResolvedArr=[]; onRejectedArr=[]; constructor(excution){ const resolve = (result) => { if(this.status === Pending){ this.result = result; this.status = Resolve; this.onResolvedArr.map((fn)=>fn()); }}; const reject = (reason) => { if(this.status === Pending){ this.reason = reason; this.status = Reject; this.onRejectedArr.map((fn)=>fn()); }}; try{ excution(resolve,reject) }catch(error){ reject(error) } } then(onResolved,onRejected){ onResolved = typeof onResolved ==="function"? onResolved:(data)=>data; onRejected = typeof onRejected ==="function"? onRejected:(err)=>{ throw new Error(err) }; Const newPromise = new JJPromise((resolve,reject)=>{if(this.status === = resolve){setTimeout(()=> Try {const result = onResolved(this.result); handlePromise(result,newPromise,resolve,reject) }catch(error){ reject(error) } },0) } if(this.status === Reject){ setTimeout(()=>{ try{ const result = onRejected(this.reason); handlePromise(result,newPromise,resolve,reject) }catch(error){ reject(error) } },0) } if(this.status === Pending){ // SetTimeOut (()=>{resolve("1111")},1000); This.onresolvedarr. push(()=>{try{const result = onResolved(this.result); HandlePromise (result, newPromise, resolve, reject) / / chain calls the second promise to perform, or does not perform} the catch (error) {reject (error)}}); this.onRejectedArr.push(()=>{ try{ const result = onRejected(this.reason); handlePromise(result,newPromise,resolve,reject) }catch(error){ reject(error) } }); } }) return newPromise; } catch(onRejected){ return this.then(undefined,onRejected) } } module.exports = JJPromise;Copy the code
Const test = new JJPromise((resolve,reject)=>{resolve(" we are the best "); }) test.then((res)=>{ console.log(res); }).then((res)=> console.log("1111") ); console.log(123);Copy the code

5. How is promise.all () implemented?

let p1=new Promise(resolve=>resolve('p1')); let p2=new Promise(resolve=>resolve('p2')); let p3=Promise.reject('p3 promise'); function promiseAll(promises){ return new Promise ((resolve,reject)=>{ let resultCount = 0; let results = new Array(promises.length); for(let i=0; i<promises.length; i++){ promises[i].then(item=>{ resultCount++; results[i]=item; if(resultCount==promises.length){ return resolve(results); } },error=>{ return reject(error) }) } }) } promiseAll([p1,p2,p3]).then(result=>{ console.log('111',result) }).catch(error=>{ console.log(error) })Copy the code

4. I promise?

1. Create a Promise instance
const promise = new Promise(function(resolve, reject) { // ... Resolve (value); resolve(value); } else { reject(error); }});Copy the code
2.Promise.prototype.then()

The first argument to the then method is the Resolved state callback and the second argument is the Rejected state callback

getJSON("/post/1.json").then(function(post) {
  return getJSON(post.commentURL);
}).then(function (comments) {
  console.log("resolved: ", comments);
}, function (err){
  console.log("rejected: ", err);
});
Copy the code
3.Promise.prototype.catch()
// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });
Copy the code

The second method is better than the first because it catches errors in the execution of the previous then method and is closer to the synchronous try/catch method. Therefore, it is recommended to always use the catch() method instead of the second argument to the then() method.

4.Promise.prototype.finally()

Method to specify actions that will be performed regardless of the final state of the Promise object

5.Promise.all()
const p = Promise.all([p1, p2, p3]);
Copy the code

Only when the states of P1, P2 and P3 become depressing, the state of P will become depressing. At this time, the return values of P1, P2 and P3 will form an array and be passed to the callback function of P.

If p1, P2, and P3 are rejected, P becomes rejected, and the return value of the first rejected instance is passed to p’s callback function

6.Promise.race()
const p = Promise.race([p1, p2, p3]);
Copy the code

In the above code, the state of P changes as long as one of the first instances of P1, P2, and P3 changes state. The return value of the first changed Promise instance is passed to p’s callback.

7.Promise.allSettled()

The promise.allSettled () method takes a set of Promise instances as parameters and wraps them into a new Promise instance. The wrapper instance will not complete until all of these parameter instances return the result, whether this is fulfilled or Rejected. This method was introduced by ES2020.

8.Promise.any()

ES2021 introduces the promise.any () method. The method takes a set of Promise instances as parameters and returns them wrapped as a new Promise instance. As long as one parameter instance becomes a depressing state, the packaging instance will become a depressing state. If all parameter instances become the Rejected state, the wrapper instance becomes the Rejected state.

Promise.any() is like the promise.race () method except that it does not end when a Promise changes to the Rejected state.

Mp.weixin.qq.com/s/6Jsz_mskT…