This is the second day of my participation in the August Challenge. For more details, see:August is more challenging

preface

This article will be the secret to the big promise level. For now, just share a summary of promises and write them by hand. More interview questions will follow to improve the essay.

The body of the

Did you know about Promise’s questions?

The definition of promise

  1. Promise is a solution to asynchronous programming

The use of the promise

  1. Promise is a constructor that generates a Promise instance with new
  2. A Promise takes a function as an argument, which takes resolve and Reject. They are two functions that are provided by the JavaScript engine and do not have to be deployed.
    • The resolve function does:
      1. Change the state of the Promise object from Pending to Resolved
      2. Called when the asynchronous operation succeeds
      3. Pass the result of the asynchronous operation as a parameter
    • The reject function works:
      1. Change the state of the Promise object from Pending to Reject
      2. Called when an asynchronous operation fails
      3. And pass the error reported by the asynchronous operation as a parameter

The characteristics of the promise

  1. The perOMise object represents an asynchronous operation. It has three states. Only the result of the asynchronous operation can determine which state, and nothing else can be affected
  2. Once the state changes, it doesn’t change again, and it can happen any time. There are only two possible state changes for a Promise object: from pending to fulfilled and from pending to rejected. As long as those two conditions occur and the state becomes frozen, it does not change and remains the same, this is called resolved. If you add a callback to the Promise object if the change has already occurred, you get the same result immediately. This is completely different from events, which have the characteristic that if you miss it and listen again, you don’t get the result.

The advantages of Promise (more writing optimizations than callback hell, mainly writing optimizations)

  1. Asynchronous operations can be expressed as synchronous operations, avoiding layers of nested callback functions.
  2. Promise objects provide a uniform interface that makes it easier to control asynchronous operations.

The shortcoming of promise

  1. You cannot cancel a Promise, it is executed as soon as it is created, and you cannot cancel it in mid-stream.
  2. If the callback function is not set, the errors thrown by the Promise internally are not reflected externally.
  3. When you are in the Pending state, you have no way of knowing where you are (just started or about to finish).

How to implement a simple version of a Promise

Function (window) {function myPromise(execotor) {let self = this self.status = 'pending' self.data = Self.callbacks = [] // {onResolved => {}, onRejected => {}} function resolve(value) { if (self.status ! == 'pending') {return} 'resolved' self.status = 'resolved' self.data = value 'resolved' If (self.callbacks. Length > 0) {setTimeout(() => {self.callbacks. ForEach (callbackObj => { callbackObj.onResolved(value) }) }, 0) } } function reject(value) { if (self.status ! == 'pending') {return} 'resolved' self.status = 'resolved' self.data = value 'resolved' If (self.callbacks. Length > 0) {setTimeout(() => {self.callbacks. ForEach (callbackObj => { callbackObj.onResolved(value) }) }, 0) } } try { execotor(resolve, Mypromise.prototype. then = function(onResolved, reject) {reject(error) {reject(error)}} // this.callbacks. Push ({onResolved, onRejected }) let self = this return new myPromise((resolve, reject) => { if (self.status === 'pending') { self.callbacks.push({ onResolved() { onResolved(self.data) }, onRejected() { onRejected(self.data) } }) } else if (self.status === 'resolved') { setTimeout(() => { const result = onResolved(self.data) if (result instanceof myPromise) { result.then( value => { resolve(value) }, reason => { reject(reason) } ) } else { resolve(result) } // onResolved(self.data) }, 0) } else { setTimeout(() => { onRejected(self.data) }, 0)}})} myPromise. Prototype. Catch = function (onRejected) {} / / promise function object on mount method myPromise. Resolve = function (value) { } myPromise.reject = function (value) { } myPromise.all = function (value) { } myPromise.race = function (value) { } global.myPromise = myPromise })() // pending // resolved // rejected let p = new myPromise((resolve, reject) => { setTimeout(() => { console.log('yes'); resolve('ok') }, 100) }) p.then(fn) .then( value => { console.log(value , 'test'); return new Promise() } )Copy the code

conclusion

The above is only the first day summary of the author, the follow-up will be improved, useful words are welcome to continue to pay attention!!