Write your own promise in promises / A + specification

nameIsZoe27 2021-05-04 11:04:46
write promise promises specification


Preface

Baidu wrote many times by others promise , It's also a whim Today I wrote one and made such a record

Promises/A+

The classmates : Check it out here Promises/A+ standard

Just do it

Next, I look at the norms according to my own habits

  1. “promise” is an object or function with a then method whose behavior conforms to this specification.

My own translation :class Promise{} and function Promise{} Will do , So what I wrote was class

 class Promise{
constructor(execuctor) {}
}
export default Promise
 Copy code 
  1. A promise must be in one of three states: pending, fulfilled, or rejected....

My own translation : Every promise There are three states , And pedding The state can be changed ( adopt resolve and reject) fulfilled, or rejected, But only one change is supported , It can't be transformed into any other state .

  1. “reason” is a value that indicates why a promise was rejected.

    “value” is any legal JavaScript value (including undefined, a thenable, or a promise).

My own translation : resolve() and reject() Parameters of And initialization of its value , combination 2 Do state change processing

//class Same level outer layer Constants that define States , Waiting to use , In practice, for the sake of readability , You usually define constants
// State constant
/** Initialization status */
const PENDING = "PENDING";
/** Success status */
const FULFILLED = "FULFILLED";
/** Failure status */
const REJECTED = "REJECTED";
class Promise{
constructor(execuctor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (val) => {
// After state change You can't change to another state at , Only one modification is supported
if (this.status === PENDING) {
this.value = val; // In the state of success value Assignment
this.status = FULFILLED; // modify state
}
};
const reject = (err) => {
// After state change You can't change to another state at , Only one modification is supported
if (this.status === PENDING) {
this.reason = err; // In the state of failure reason Assignment
this.status = REJECTED; // modify state
}
}
}
 Copy code 
  1. “exception” is a value that is thrown using the throw statement.

My own translation :throw Exception thrown by statement . Here, according to my own understanding use try,catch When catching exceptions call reject(err)

try {
execuctor(resolve, reject);
} catch (err) {
reject(err);
}
 Copy code 
  1. A promise’s then method accepts two arguments: promise.then(onFulfilled, onRejected)....

My own translation :then Method support ,FULFILLED perform onFulfilled,REJECTED perform onRejected And the parameters have to be functions , We don't paste all the specifications here

then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value);
}
if (this.status === REJECTED) {
onRejected(this.reason);
}
 Copy code 

Complete code

class Promise {
constructor(execuctor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
const resolve = (val) => {
// After state change You can't change to another state at , Only one modification is supported
if (this.status === PENDING) {
this.value = val; // In the state of success value Assignment
this.status = FULFILLED; // modify state
}
};
const reject = (err) => {
// After state change You can't change to another state at , Only one modification is supported
if (this.status === PENDING) {
this.reason = err; // In the state of failure reason Assignment
this.status = REJECTED; // modify state
}
};
try {
execuctor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
//then Parameters of resolve function , and reject function
if (this.status === FULFILLED) {
onFulfilled(this.value);
}
if (this.status === REJECTED) {
onRejected(this.reason);
}
}
}
export default Promise
 Copy code 

We test the results The test plug-in uses code run ( Follow the guidelines VS code Plug in sharing --- Run Code)

image.png

image.png

Summary

Here is a simple promise Full code , It's too late. I'll write it next time

版权声明
本文为[nameIsZoe27]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210504110147684Y.html

  1. JS: event flow
  2. Front end performance optimization: rearrangement and redrawing
  3. JS - deep and shallow copy
  4. JavaScript异步编程3——Promise的链式使用
  5. JavaScript asynchronous programming 3 -- chain use of promise
  6. Vue.js组件的使用
  7. The use of vue.js component
  8. How to judge whether a linked list has links
  9. Element UI custom theme configuration
  10. Text image parallax effect HTML + CSS + JS
  11. Spring的nohttp宣言:消灭http://
  12. Vue3 intermediate guide - composition API
  13. Analysis of URL
  14. These 10 widgets that every developer must know
  15. Spring's nohttp Manifesto: eliminate http://
  16. Learn more about JS prototypes
  17. Refer to await to JS to write an await error handling
  18. A short article will directly let you understand what the event loop mechanism is
  19. Vue3 uses mitt for component communication
  20. Characteristics and thinking of ES6 symbol
  21. Two way linked list: I'm no longer one-way driving
  22. Vue event and form processing
  23. Reactive TraderCloud实时外汇开源交易平台
  24. Reactive tradercloud real time foreign exchange open source trading platform
  25. Node.js REST API的10个最佳实践
  26. Ten best practices of node.js rest API
  27. Fiddler advanced usage
  28. Process from Vue template to render
  29. Promise up (asynchronous or synchronous)
  30. Principle and implementation of promise
  31. Vs code plug in sharing - run code
  32. Vue practical notes (1) introduction of Ant Design
  33. Vue actual combat notes (2) introduction of element plus
  34. Introduction to webpack
  35. Webpack construction process
  36. Vue notes
  37. The experience and lessons of moving from ruby megalith architecture to go microservice
  38. Using leancloud to add artitalk module to hexo blog
  39. Implementation of chrome request filtering extension
  40. Detailed introduction of beer import declaration elements and label quarantine [import knowledge]
  41. Gallop workflow engine design series 01 process element design
  42. VUE移动端音乐APP学习【十六】:播放器歌词显示开发
  43. Vue Mobile Music App learning [16]: player lyrics display development
  44. jquery cookie
  45. jquery cookie
  46. 体面编码之JavaScript
  47. JavaScript for decent coding
  48. React17 系统精讲 结合TS打造旅游电商平台
  49. React17 system combined with TS to build tourism e-commerce platform
  50. 2021-05-04 hot news
  51. HttpSession对象与Cooike的关系 以及 Cookie对象构造函数问题
  52. gRPC-Web:替代REST的gRPC的Javascript库包
  53. The relationship between httpsession object and cooike and the construction of cookie object
  54. Grpc Web: a JavaScript library package to replace rest grpc
  55. Building reactive rest API with Java - kalpa Senanayake
  56. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  57. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  58. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  59. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  60. Vue.js比jQuery更容易学习