Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
One, foreword
In the previous article, I introduced the analysis of Promise’s related functions and features with examples, including the following contents:
- Promise base features;
- Promise instance API (prototype method);
- Promise static API (class methods);
- Feature analysis of Promise in different scenarios;
This article, according to the previous analysis and understanding of Promise, to achieve a simple version of Promise;
Two, the implementation of the Promise
Based on the previous understanding and analysis of the use of Promise, Promise has the following key features:
- Promise is a class;
- The constructor takes an excutor function;
- The arguments to this function are resolve and reject inner functions;
- Build resolve and Reject, pass excutor, and make it execute immediately;
- The Promise class has three states, which default to wait;
- Change the status of resolve and Reject.
- The Promise class contains methods like then and catch;
So, a Promise looks like this:
class Promise(a){
constructor (fun) {
this.status = 'pending'; // Status: pending, depressing, rejected
fun(this.resolve, this.reject); // The body function will be executed immediately
}
resolve() {}
reject() {}
then() {}
catch() {}}Copy the code
Iii. Promise A+ Specification (Simplified version)
The above code is based on the understanding of the “guess”, more rigorous should be implemented according to the Promise A+ specification;
Note: This article only introduces the basic part of the Promise A+ specification, which is used to support the implementation of the simplified Promise;
1. Technical points
- 1.1 Promise is an object or function. There should be a THEN method, and the THEN method should comply with the specification.
- 1.2 Thenable is an object or function
- 1.3 Value is a valid JS value, which can be undefined, a Thenable object, or a Promise object.
- 1.4 Exceptions can be thrown using the throw code block
- 1.5 reson is a value that tells us why the promise was rejected
Simple analysis:
- Promises can be implemented in many ways, either as objects or functions; Can meet the standard;
- Because the Promise instance can
.then
, so we think of the Promise instance as a Thenable object; - Call reslove() to pass in a value, or undefined, or promise or thenable;
2. Necessary
2.1 promise state
Promise has three states: pending, a pity success and rejected failure.
- 2.1.1 When the Promise is pending, it can be changed to a depressing success state or rejected failure state.
- 2.1.2 When the promise is a big success
- 2.1.2.1 Cannot be changed to other states
- 2.1.2.2 There must be a value and it cannot be changed
- 2.1.3 When the Promise state is Rejected
- 2.1.3.1 Cannot be changed to other states
- 2.1.3.2 There must be a cause and it cannot be changed
2.2 Then is a method
A promise must have a THEN method and access successful or failed values; A promise can accept two parameters, onFulfilled and onRejected.
. Skip the rest for the moment…
Note: Understand the above content, enough to support the implementation of simplified Promise;
So, you can implement a simplified Promise based on the following five points:
1, Promise is a class; 2. when a promise is used, the executor executor is passed in and immediately executed. The executor parameter is two functions that describe the state of a Promise instance. Resolve indicates success, and a value can be passed. Reject indicates failure. You can pass in a reason. 4. Each Promise instance has a THEN method; 5. Once a promise state occurs, it cannot be changed. A promise has three states: success state, failure state and wait state (default).Copy the code
Four, realize the simplified Promise
// Declare three states of promise
const PENDING = 'PENDING'; / / wait state
const DULFILLED = 'DULFILLED'; / / success
const REJECTED = 'REJECTED'; / / failure mode
class Promise{
// The executor executor function is passed in when instantiated through a new Promise
constructor(executor){
this.value = undefined; // Save the reason for success, which will be passed in when ondepressing is called in then
this.reason = undefined; // Save the reason for the failure, which will be passed in when ondepressing is called in then
this.state = PENDING; // Promise state, default wait state
// Reslove succeeds, reject fails, and executor is passed
const reslove = (value) = >{
// Wait state --> Success state
if(this.state === PENDING){
this.value = value
this.state = DULFILLED; }}const reject = (reason) = >{
// Wait state --> failed state
if(this.state === PENDING){
this.reason = reason
this.state = REJECTED; }}// Execute the executor executor function immediately, using the try... catch... To catch exceptions;
try{
executor(reslove, reject);
}catch(e){
reject(e) Reject (reject) reject (reject}}// Define the then method: onFulfilled and onRejected;
// According to the Promise state, perform onFulfilled or onRejected;
then(onFulfilled, onRejected){
// Call ondepressing and pass in success value
if(this.state === DULFILLED){
onFulfilled(this.value)
}
// In failed state, execute onRejected and pass in failed reason
if(this.state === REJECTED){
onRejected(this.reason)
}
}
}
Export the Promise class for external use
module.exports = Promise;
Copy the code
Test promise basic features:
// 1, introduce a simplified version of Promise
let Promise = require('./source/promise');
// 2. Instantiate the Promise and pass in the Executor executor function (which will be executed immediately)
let promise = new Promise((resolve, reject) = >{
console.log('promise')
throw new Error("Throw an error");
})
// then method
promise.then((value) = >{
console.log('success', value)
},(reason) = >{
console.log('err', reason)
})
console.log('ok')
// Execution result
promise
err Error: Throws an errorCopy the code
This completes a simplified (implied) version of the Promise;
Five, the end
This article, based on the analysis and understanding of Promise, realizes a simple Promise, mainly involving the following contents:
- Promise implementation ideas;
- Promise A+ specification (simplified version);
- Promise simplified implementation and functional testing;
Next, translate and understand the Promise A+ specification;
Maintain a log
- 20211120:
- Correct typos