1. Why do promises come into being

Promise is an asynchronous solution because promises make asynchronous callbacks easier, with the following characteristics

  • There are three states of the Promise, which is pending, a pity and a failure. Only the code execution result passed in by the constructor will change the Promise state (I will call the successful state as resolved later).
  • It will be executed as soon as it is created
  • The code passed in the Promise constructor is executed immediately, but then is a microtask

Basic use of Promise

let p = new Promise((resolve, reject) => {
    let result = ''
    // code
    if(result == 200) {
        resolve()
    }else {
        reject()
    }
})
Copy the code

  • The constructor takes a function that takes resolve and reject. The body of the function usually contains an asynchronous request
  • The new creation is executed, and the above code executes as soon as it is parsed

Resolve and reject

  • Resolve: The resolve function updates the Promise state from pending to Resolved and executes the first parameter in promise. then
  • Reject: Reject updates the Promise state from pending to Reject and executes the second parameter in promise. then

Four, Promise. Then

  • Then passes two arguments to then, the first corresponding to resolve and the second to reject

    let p = new Promise((resolve, reject) => { let result = ” // code if(result == 200) { resolve() }else { reject() }})p.then((value) => { console.log(value)}, (error) => { console.log(error)})

Five, the Promise. The catch

  • If the result of the first argument in then is null or undefined, the catch is executed

    let p = new Promise((resolve, reject) => { let result = ” // code if(result == 200) { resolve() }else { reject() } }) p.then((value) => { return undefined }, (error) => { console.log(error) }).catch( err => { console.log(err) })

    // the result of the above code is undefined

Six, Promise. Finally

  • Action: Action that will be performed regardless of the final state of the Promise

    let p = new Promise((resolve, reject) => { let result = ” // code if(result == 200) { resolve() }else { reject() } }) p.then((value) => { return undefined }, (error) => { console.log(error) }).catch( err => { console.log(err) }).finally(() => { console.log(‘finally’) }) // undefined finally

Seven, promise. All

  • What it does: Wraps multiple promises into a single Promise instance, passing in an array of parameters, each array element being a Promise

  • Features: Only when each Promise returns a big Promise, the state of the newly encapsulated Promise will be successful. Otherwise, as long as one of the promises fails, it will be a failure state

    Const Promises = [2, 3, 5, 7, 11, 13]. Map ((id) => {return getJSON(‘/post/’ + id + “. Json “); // Generate an array of promises const Promises = [2, 3, 5, 7, 11, 13]. });

    Promise.all(promises).then( (posts) => { // … }).catch((reason) => { // … });

Write promises by hand

function PromiseFun(f) { this.status = 'pending'; this.resolveCallback = function() {} this.rejectCallback = function() {} this.catchCallback = function() {} this.finallyCallback = function() {} f() function resovle(value) { this.status = 'fulfilled' return this.resolveCallback(value) } function reject(error) { this.status = 'rejected' return this.rejectCallback(error) } } PromiseFun.prototype.then = function (f1, f2) { this.resolveCallback = f1 this.rejectCallback = f2 } PromiseFun.prototype.catch = function (f) { this.catchCallback = f } PromiseFun.prototype.finally = function (f) { this.finallyCallback = f } function f(resolve, reject) { let result = 200 if(result === 200) { resolve(result) }else { reject(result) } } let p = new Promise(f).then((v) => {console.log(" I am a parameter f1") console.log(v)}, (e) => {console.log(" I am parameter f2") console.log(e)}) // Prints the result I am parameter F1 200Copy the code