Writing in the front

Resolve () or reject() tells us to return a Promise with an end result or a reason for rejection.

Three states of Promise

  • hang
  • Has been successfully
  • Has been completed

The latter two are states after an asynchronous operation has completed

Promise to do guarantee

The Promise object is used to represent the final state (completion or failure) of an asynchronous operation and the value it returns.

As defined above, MDN makes promises that tell us the status of asynchronous operations. Details are as follows:

  • Call the callback function after the current event queue completes execution
  • The callback function is added via THEN
  • By adding multiple THEN, you can add multiple callback functions to execute one after the other

Promise chain call

Existing requirements: Sometimes we need to call multiple asynchronous operations in a row, each after the previous result. There used to be callback functions, which could easily lead to callback hell. With promises, success/failure of each action is followed by the result of the next action.

// Call back to hell
doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
        console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

// After using the Promise chain call
doSomething().then(function(result) {
  return doSomethingElse(result);
})
.then(function(newResult) {
  return doThirdThing(newResult);
})
.then(function(finalResult) {
  console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
Copy the code

Error handling

In code snippet 1 above, there are three error callbacks. In a Promise chain call, an error-handling callback is added at the end. When an error is thrown, a Promise with the reason for the error is returned to the next catch, all the way to the bottom of the catch function.

// Initial Do that
new Promise((resolve, reject) = > {
    console.log('Initial');
    resolve();
})
.then((a)= > {
    throw new Error('Something failed');
    console.log('Do this');
})
.then((a)= > {
    console.log('Do this whatever happened before');
})
.catch((a)= > {
    console.log('Do that');
})
Copy the code

In addition, if an exception is caught midway, then it can continue:

* Initial * Do that * Do this whatever happened before */
new Promise((resolve, reject) = > {
    console.log('Initial');
    resolve();
})
.then((a)= > {
    throw new Error('Something failed');
    console.log('Do this');
})
.catch((a)= > {
    console.log('Do that');
})
.then((a)= > {
    console.log('Do this whatever happened before');
})
Copy the code

The reason is that catch(failureCallback) is itself an abbreviated form of THEN (NULL), which returns a Promise with the current state. We can also catch exception information in the following way:

* Initial * Something failed * Do that * Do this whatever happened before */
new Promise((resolve, reject) = > {
    console.log('Initial');
    resolve();
})
.then((a)= > {
    throw new Error('Something failed');
    console.log('Do this');
})
.catch((e) = > {
    console.log(e.message)
    console.log('Do that');
})
.then((a)= > {
    console.log('Do this whatever happened before');
})
Copy the code

Use async/await syntax sugar

A chestnut

/ / use the Promise
doSth()
    .then(res= > doSthElse(res))
    .then(newRes= > doThirdTh(newRes))
    .then(finalRes= > {
        console.log(`finalResult is ${finalRes}`)})// Write asynchronous code in a synchronous style with async/await
async funtion foo () {
    let res = await doSth()
    let newRes = await doSthElse(res)
    let finalRes = await doThirdTh(newRes)
    console.log(`finalResult is ${finalRes}`)}Copy the code

Promise. Resolve (), Promise. Reject (

Use these two static methods to create a resolve or reject guarantee as follows:

getRecommend () {
    let today = new Date(a)let date = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate(), 9)
    
    return axios.get(`/api/getRecommend? date=The ${Number(date)}`
    ).then(response= > {
      return Promise.resolve(response.data)
    }).catch(err= > {
      console.log(err)
    })
}
Copy the code

When/API /getRecommend () is successfully requested using AXIos, Axios returns a Promise object. Since getRecommend() is exported, a state-completed Promise is returned directly. When getRecommend() is called, If the response is successful, recommend.getrecommend ().then(res => {}).

Promise.all() and promise.race () execute multiple Promise objects in parallel

  • Promise.all()It ends when all Promise objects are in the ‘Succeeded’ state
  • Promise.race()There is a Promise object state that ends with ‘success’

Promise serial execution

Promise chain call

The following summation example shows a good example of passing values between promises:

// Execute the XXX operation to ensure that *** results
let step1 = function () {
  let val = 1
  console.log(`this is step1 , the value is ${val}`)
  // In the case of rejection, Balalala...
  if (val > 0) {return Promise.resolve(val)
  }
  return Promise.reject(val)
}
// Execute the XXX operation to ensure the *** result
let step2 = function (val) {
  val += 1
  console.log(`this is step2 , the value is ${val}`)
  return Promise.resolve(val)
}
// Execute the XXX operation to ensure that *** results
let step3 = function (val) {
  val += 1
  console.log(`this is step3 , the value is ${val}`)
  return Promise.resolve(val)
}

step1().then((val) = >{
  return step2(val)
}).then((val) = >{
  return step3(val)
}).then((val) = >{
  console.log(`finally, the value is ${val}`)})// Output the result
this is step1 , the value is 1
this is step2 , the value is 2
this is step3 , the value is 3
Copy the code

aysnc/await

Add again with async/await syntax sugar

// We treat each step as asynchronous here
function step21() {
  let val = 1
  console.log(`this is step1 , the value is ${val}`)
  return val
}

function step22(val) {
  val += 1
  console.log(`this is step2 , the value is ${val}`)
  return val
}

function step23(val) {
  val += 1
  console.log(`this is step3 , the value is ${val}`)
  return val
}

(async() = > {// await must be used within async functions
  let val = await step21()
  val = await step22(val)
  val = await step23(val)
})()

// Output the result
this is step1 , the value is 1
this is step2 , the value is 2
this is step3 , the value is 3
Copy the code

Promise array serial

Using the array’s reduce() method,

// Execute the XXX operation to ensure that *** results
let step1 = function () {
  let val = 1
  console.log(`this is step1 , the value is ${val}`)
  // In the case of rejection, Balalala...
  if (val > 0) {return Promise.resolve(val)
  }
  return Promise.reject(val)
}
// Execute the XXX operation to ensure the *** result
let step2 = function (val) {
  val += 1
  console.log(`this is step2 , the value is ${val}`)
  return Promise.resolve(val)
}
// Execute the XXX operation to ensure that *** results
let step3 = function (val) {
  val += 1
  console.log(`this is step3 , the value is ${val}`)
  return Promise.resolve(val)
}

let steps = [step1, step2, step3]
steps.reduce((promise, fn, index) = >{
  console.log(index)
  return promise.then((val) = >{
    return fn(val)
  })
  // reduce function init parameter
}, Promise.resolve())

// Output the result
this is step1 , the value is 1
this is step2 , the value is 2
this is step3 , the value is 3
Copy the code

Async /await array serial

Just think of the Array method, using array.prptotype.reduce () as the solution, or do not have a deep understanding of how reduce() is implemented

async function foo () {
  let val
  for (let i = 0; i < steps.length; i++) {
    if (i===0) {
      val = await steps[i]()
    }else {
      val = await steps[i](val)
    }
  }
}
foo()
Copy the code