Basic use of Promise
let promise = new Promise((resolve,reject) = >{
setTimeout(() = >{
resolve(1)},1000)})//1. Call "success/failure" via thene. catch
promise.then(res= >{console.log('Successful callback',res)})
.catch(err= >{console.log('Failed callback',err)})
//2. Use the second argument then to handle "failed, callback"
promise.then(res= >{console.log('Successful callback',res)},
err= >{console.log('Failed callback',err)})
Copy the code
Promise can handle callbacks through the method of THEN, which has two arguments, the first triggering a callback to resolve (success) and the second to reject (failure). It is recommended to use the catch notation to catch exceptions
Principle of Promise
Promise
It’s actually a constructor that, when we call it, passesnew Promise
To create an instance and process it through a chain callnew Promise
Is a synchronization task,Promise
thethen
The method is aMicro tasks
When the context is executed, the promise is executed immediately, while the then method is executed after the main thread is executed. (Here it isEvent loop
)
Write a basic Promise by hand
class WPromise {
static PENDING = "pengding";
static FUFILLED = "fulfilled";
static REJECTED = "rejected";
constructor(executor) {
this.status = WPromise.PENDING;
this.value = null;
executor(this._resolve.bind(this), this._reject.bind(this));
}
_resolve(value) {
if (this.status === WPromise.PENDING) {
this.status = WPromise.FUFILLED;
this.value = value; }}_reject(reason) {
if (this.status === WPromise.PENDING) {
this.status = WPromise.REJECTED;
this.value = reason; }}then(res, req) {
if (this.status === WPromise.FUFILLED && res) {
res(this.value);
}
if (this.status === WPromise.REJECTED && req) {
req(this.value); }}}new WPromise((resolve, reject) = > {
resolve(5);
resolve(6);
reject(7);
}).then(
(res) = > {
console.log("Success", res);
},
(err) = > {
console.log("Failure", err); });Copy the code