What is a Promise

Promises are a solution to asynchronous programming: syntactically, promises are an object from which to retrieve messages for asynchronous operations; In its original sense, it is a promise that will give you results over time. Promise has three states:Pending, fulfiled, Rejected; Once the state has changed, it will never change. Once a Promise instance is created, it executes immediately.

The role of the Promise

Promises are designed to solve two problems:

  • Callback hell, code is difficult to maintain, often the output of the first function is the input of the second function
  • Promises can support multiple concurrent requests, retrieving data from concurrent requests

I wrote the callback form before

The function fn (a, fn2) {if (a > 1) {fn2 ()}} fn (2, function () {the console. The log (" hello ")})Copy the code
let p = new Promise(((resolve, Reject) = > {/ / perform some asynchronous operations setTimeout (() = > {the console. The log (" I performed ") resolve (" I am a successful ")}, 3000)})) p.t hen ((res) = > { console.log(res) },(err) => { console.log(err) })Copy the code

The Promise constructor takes one argument, function(resolve,reject), and the function takes two arguments:

  • Resolve: Callback function after asynchronous operation is successfully executed
  • Reject: Callback function when an asynchronous operation fails

Two arguments are passed in then, and the THEN method can accept two arguments, the first corresponding to the resolve callback and the second to the reject callback

The effect of a catch is the same as the effect of the second function of THEN, but if an exception is thrown when the resolve callback (the first argument to then above) is executed, the js will not be stuck, but instead will be thrown into the catch method. This function is the same as try-catch.

Here’s the code for the chain call

Notice how to return a new Promise in then, and the use of two syntactic sugars

  1. Promise.reslove()

  2. return …

  3. return new Promise()

let p = new Promise(((resolve, Reject) => {// Perform some asynchronous operations setTimeout(() => {var a = 3 resolve(a) // reject(b)},3000)}))) p.hen ((data) => { console.log(data); Return new Promise((resolve,reject) => {var s = "resolve(s)})}). Then ((data) => {console.log(data); Return promise.reject (" reject ")}). Then ((data) => {console.log(data); },(err) => { console.log(err) return 1111 }) .then((data) => { console.log(data); })Copy the code

Promise.all

Promise. All features:

  • The input parameter is composed of multiple inputsPromiseAn array of instances
  • The return value ispromiseBecause it can be used.then
  • If all are successful, the status becomesresolvedAnd the return values form an array to pass to the callback
  • If there is a failure, the state becomesrejectedAnd willerrorReturn to the callback
Function myPromiseAll(p){return new Promise(resolve,reject) => {if(! Array.isArray(p)){ throw new TypeError("promises must be an array") } let result = []; let count = 0; P.foreach ((Promise,index) => {Promise. Then ((res) => {result.push(res) Because forEach is an asynchronous task, using push might cause the res to be in the wrong order. Promise.all returns in the same order. Result [index] = res count++ // Count === p.length && resolve(result)},(err) => {reject(err)})})}) Promise.resolve(1), p2 = Promise.resolve(2), p3 = Promise.resolve(3); myPromiseAll([p1, p2, p3]).then((res)=>{ console.log(res, 'res') }, (err)=>{ console.log(err, 'err') }) //[ 1, 2, 3 ] resCopy the code

Realize the Promise. Race

function myPromiseRace(p){
    return new Promise((resolve,reject) => {
        p.forEach((promise,index) => {
            Promise.resolve(promise).then((value) => {
                resolve(value)
            },(reason) => {
                reject(reason)
            })
        })
    })
}
let p1 = new Promise(((resolve, reject) => {
    setTimeout(() => {
        var a = 1
        resolve(a)
    },1000)
}))
let p2 = new Promise(((resolve, reject) => {
    setTimeout(() => {
        var b = 2
        resolve(b)
    })
}))
let p3 = new Promise(((resolve, reject) => {
    reject(3)
}))
let p = [p1,p2,p3]
myPromiseRace(p).then((res)=> {
    console.log(res)
},(err) => {
    console.log(err)
})
Copy the code

Completing forEach is an asynchronous task, so it can be used to implement promise.race