Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

promise API

  • What is an API?
    • An API is a set of predefined interfaces (such as functions, HTTP interfaces).
    • Simplified definition: The API here refers to the method of a function
  • A brief introduction to some APIS? What are the roles of the two
/* Promise constructor: Promise(excutor) {} Excutor (resolve, reject)=>{} Resolve (reject)=>{} Resolve (reject)=>{} Reject (reject)=> Note: Excutor immediately synchronizes the callback inside a promise, and the asynchronous operation executes the promise.prototype. then method in the executor: (onResolved,onRejected)=>{} onResolved (value)=>{} onRejected Return a new promise object (promise.prototype. catch method) : {return a new promise object (promise.prototype. catch); (onRejected) = > {} onRejected function: the failure of the callback function (reason) = > {}, then () of syntactic sugar then (undefined, onRejected) Promise. Resolve method: (value)=>{} Value: successful data or promise object note: Return a successful or failed promise object promise. reject method: (reason)=>{} Reason: failure reason note: Promise.all: (promises)=>{} Promises: promises: n promises Promises =>{} promises: promises (promises)=>{} Promises: promises (promises) Return a promise. The first completed promise results in the final result state */
Copy the code

Examples of API usage

new Promise((resolve, reject) = >{
    setTimeout(() = >{
        // Two functions can only run one promise state
        resolve('success')
        // reject(' reject ')
    },1000)
}).then(
    // chain call onResolved
    value= >{
        console.log('onResolved()',value)
    }
).catch(
    // Catch the error call function onRejected
    reason= >{
    console.log('onRejected()',reason)
    }
)
Copy the code

Promise syntactic sugar

 // The initial writing of a promise object with a success value of 1
 const p1 = new Promise((resolve,reject) = >{
     resolve(1)
 })
 p1.then(value= >{console.log(value)})
 
 //
 const p2 = Promise.resolve(1)
 p2.then(value= >{console.log(value)})
 
 // Generate a promise object with a failure value of 1
 const p3 = Promise.reject(1)
 // There are two ways to get a value on failure
 p3.then((null,reason) = >{console.log(reason)})
 p3.catch(reason= >{console.log(reason)})
Copy the code

conclusion

  • There are many boring knowledge points today, which need to be digested slowly. The rest of the API will be more in the next period
  • Keep an eye on the column Promise continues to update…