What is a Promise

The Promise object is a JavaScript asynchronous operation solution that provides a unified interface for asynchronous operations. Promise allows asynchronous operations to be written as if they were the flow of synchronous operations, rather than having layers of nested callback functions. It’s what we call callback hell.

How to fulfill a Promise?

The first part

Before we implement it, let’s take a look at some of its features, which will make it easier to understand when we implement it.

  1. There are three states. The default is pending, which is a pity and rejected
  2. You must pass a function when creating it, otherwise an error will be reported
  3. The arguments in the pass function are two callback functions, resolve and reject
  4. Once a state changes, it doesn’t change

There are many features and we will implement them slowly

Class MyPromise{constructor(fn) {// 2: Promise must receive a function or return an error if (! This.isfunc (fn)){throw new Error(' This is not a function ')} this.isfunc (fn)){this.isfunc (fn)){throw new Error(' this is not a function ')} Resolve and reject this. Resolve = (data) =>{ This. Status = 'depressing'}} this. Reject = (data) =>{if (this. Status === 'pending'){this IsFunc (fn){return typeof === 'pending'){this.status = 'rejected'}} fn(this.resolve,this.reject) Fn === 'function'}} let a = new MyPromise(function (resolve,reject){resolve() console.log(' execute '); }) console.log(a);Copy the code

If you look at the execution result, the status is already successful

The second part

Talk about the other features

  1. Multiple THEN listeners can be added to the same Promise object, and state changes are executed in the order they are listened to
  2. The then method returns a new Promise object each time it completes execution
  3. The then method of the previous Promise object can pass arguments to the then of the new Promise returned
  4. Regardless of whether the previous argument was passed in a successful or failed callback for then, the successful callback in the new Promise object’s THEN method is passed
  5. If the previous pass was a Promise object, the success or failure of the pass to the next is determined by the Promsie status passed

There’s something wrong with the code block, put an image

Take a look at the results:

The tricky part here may be determining the value of the then return, because the next promise inherits the state of the previous promise, because if the then return is a promise object, the state of the next promise will follow that return.

The third part

Last point. It is also a supplement to the above foundation

  1. The promise returned by THEN can catch exceptions in the current THEN method

  2. Catch is the syntactic sugar for then

Redundant comments I first removed, the following is the full version

class MyPromise{ constructor(fn) { if (! This.isfunc (fn)){throw new Error(' This is not a function ')} this.status = 'pending' // Define two attributes to hold this.value = in resolve and reject OnSuccessCallbacks = [] this.onSuccessCallbacks = [] this.onFailCallbacks = [] // There are two callback arguments in the function argument; Resolve and reject this. Resolve = (data) =>{ If (this.status === 'pending'){this.status = 'depressing' this.value = data if (this.onSuccessCallbacks){ this.onSuccessCallbacks.forEach((fn) => { fn(this.value) }) } } } this.reject = (data) =>{ if  (this.status === 'pending'){ this.status = 'rejected' this.fail = data if (this.onFailCallbacks){ this.onFailCallbacks.forEach((fn) => { fn(this.fail) }) } } } fn(this.resolve,this.reject) } then(onSuccess,onFail){ Return new MyPromise((nextSuccess,nextFail) => {// Then returns a promise that catches an exception in the current then method // So we can use a try catch to catch an exception (this.isFunc(onSuccess)){ if (this.status === 'fulfilled'){ let res = onSuccess(this.value) if (res instanceof MyPromise){ res.then(nextSuccess,nextFail) }else if (res ! == undefined){nextSuccess(res)}else {nextSuccess()}}catch (e) {nextFail(e)} try { if (this.isFunc(onFail)){ if (this.status === 'rejected'){ let res = onFail(this.fail) if (res instanceof MyPromise){ res.then(nextSuccess,nextFail) }else if (res ! NextSuccess (res)}else {nextFail()}} }else if (onFail === undefined){if (this.fail){nextFail(this.fail)}}catch (e) {nextFail(e)} // Solve the problem of delay correction if (this. The status = = = "pending") {if (this. IsFunc (onSuccess)) {this. OnSuccessCallbacks. Push (() = > {try {let res = onSuccess(this.value) if (res instanceof MyPromise){ res.then(nextSuccess,nextFail) }else if (res ! == undefined){ nextSuccess(res) }else { nextSuccess() } }catch (e) { nextFail(e) } }) } if (this.isFunc(onFail)){ this.onFailCallbacks.push(() => { try { let res = onFail(this.fail) if (res instanceof MyPromise){ res.then(nextSuccess,nextFail) }else if (res ! == undefined){ nextSuccess(res) }else { nextFail() } }catch (e) { nextFail(e) } }) }else if (onFail === undefined){ This. OnFailCallbacks. Push (nextFail)}}})} / / catch can be thought of as a syntactic sugar then catch (onFail) {return this. Then (undefined, IsFunc (fn){return typeof fn === 'function'}} let a = new MyPromise(function) (resolve,reject){resolve('xyz') // reject('xyz') console.log(' execute '); }) let b = a.hen (function (data) {console.log(data,' success '); xxx }) b.then(function (data) { console.log(data); },function (data) { console.log(data,'sss'); })Copy the code

Let’s look at the results

Here the next promise successfully captures the error in the previous THEN

Other methods of Promise

All methods

The all method of a Promise takes an array containing the Promise objects, executes the then method only if all the promises in the array are successful, and returns all the successful results in an array in the order they were added. If one fails, the failed callback is immediately executed.

We either succeed together or we fail together

Static all(list){// Because all is a static method, Let arr = [] return new MyPromise((resolve,reject) => {list.foreach ((value) => {value. Then ((data) => { arr.push(data) },(error) =>{ reject(error) }) }) resolve(arr) }) }Copy the code

  

Race method

The RACE method of a Promise receives an array of Promise objects. But it depends on the state of the first promise in the array

Static race(list){return new MyPromise((resolve,reject)=>{list. ForEach ((value) =>{list. value.then(function (data) { resolve(data) },function (error) { reject(error) }) }) }) }Copy the code

conclusion

My presentation may not be very good, it may not be easy to understand, and there may be mistakes that I didn’t check out. Please include 😊