The first blog of the New Year, I have been writing JS for more than a year. I feel that I just understand the surface and have not studied thoroughly. It is completely blank about the front end, and I feel deeply worried after reading other people’s interview experience. Just a few years ago, the project of reconstruction was basically stable, so I was bored and wanted to study the code. Promise has been used since ES5. I am quite familiar with then/catch, but I still don’t know the principle inside, so I took this opportunity to have a deeper understanding

References:

  • Promises/A + specification

  • The blog of God Cui Pengfei

  • Promise Test Library (872 tests)

From my results, I can almost complete the code by following the rules of the specification line by line and running it over and over with the test library, and there is a similar feeling of running through the level (see submitting records), which is pretty cool, you can try it.

Because the specification is too detailed, there is basically no good introduction, let’s talk about some points to pay attention to:

  • “Resolved” and “rejected”.
  • Spec 2.2.4: onFulfilled or onRejected can’t run until only platform code is left in the bottom stack; This means that the two functions need to be executed asynchronously (even when the Promise is resolved). SetTimeout and Node specific setImmediate and Process. nextTick are common examples of asynchronous execution. Differences in specific functions can affect the effectiveness of the overall Promise implementation, which you can focus on here
  • Specification 2.2.6.1: When the Promise enters the fulfilled state, all ondepressing needs to be triggered according to the order in which they invoke THEN. The implication here is that the functions passed in then are triggered by active callbacks, which means that promises are essentially a wrapper around callbacks, with strict restrictions on state and specification that make them easier to use in the end
  • Specification 2.3: Promise resolver, expressed as [[Resolve]](Promise, x), essentially writes a function, enters an unfinished Promise and the value x, and runs a series of rules to determine the final state of the Promise. This part is the core of the Promise specification, because the rule is so detailed that it can be followed almost anywhere. Focus: Make sure that functions you pass into X. Chen can only be called once, and always try catch the whole time

Promise library


Did this article help you? Welcome to join the front End learning Group wechat group: