Why promise promise core

Why use a promise

1. Using a pure callback function

First specify a callback function, and then start asynchronous tasks

1. A way to specify a callback function is more flexible

You can perform tasks before, during and after

2. Support chained calls, callback hell to solve the problem

What is hell Callback: callback function nested, one result of the callback function dependent on a lower layer of callback

solution. promise Chain

The ultimate solution async / await

async function request() {
  try {
    const result = await dosongthing()
    const newResult = await doThirdThing(result)
    const finalResult = await doThirdThing2(newResult)
  } catch (error) {
    failureCallback(error)
  }
}

How to use the promise? Figure out the syntax (API: front and rear interfaces)

Given a function, it is the definition of a api. Because that is a grammar

 

1.Promise Constructor: Promise (excutor) {}

excutor functions: perform synchronization (resolve, reject) => {}

resolve function: internal definition of success when we call the function value => {}

reject function: defines internal failure reason we call function => {}

Description: excutor sentence will do synchronous calls immediately Promise, asynchronous operations performed in the actuator

 

2.Promise.prototype.then方法 (onResolved,onRejected)=> {}

onResolved function: When a successful callback function (value) => {}

onRejected function: when the failure callback function (reason) => {}

Returns a new promise a prerequisite for objects // chained calls

 

3.Promise.prototype.catch方法 (onRejected)=> {}

onRejected function: when the failure callback function (reason) => {}

Corresponds then (null, onRejected) => {}

new Promise((a, b) => {
  setTimeout(() => {
    // a('ok')
    b('fail')
  }, 0)
}).then(
  value => {
    console.log('onResolved1', value)
  }
).catch(
  reason => {
    console.log('onReject', reason)
  }
)

 

4.Promise.all方法 (promise)=> {}

promise: promise array comprising n

// return a promise Object

Three requests are successful only shows success

5.Promise.race方法 (promise)=> {}

promise: promise array comprising n

The first complete look at the first execution

Guess you like

Origin www.cnblogs.com/-constructor/p/12219802.html