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

Promise Basics

Promise to understand
  • Promise is the new solution to asynchronous programming in javascript
  • Promise is a constructor
  • The Promise object is used to encapsulate an asynchronous operation and get the result
State of promise
  • Pending waiting state
  • Resolved
  • Rejected State
Promise state transition
graph TD
pending --> resolved
pending --> rejected
  • There are only two types of state transitions
  • A promise object can only change state once
  • If the operation succeeds, the result is Value. If the operation fails, the result is Reason
Basic Promise process

  • New Promise() Create a Promise
  • Successfully execute Resolved ()
  • Failed to execute rejected()
  • Resolved and Rejected callbacks can be used. Then
  • Catch can only be used in the Rejected callback
  • A promise returns a promise object
Basic use of promise
        // 1. Create a promise
        // 2. promise receives a callback function called an executor function that performs an asynchronous task
        // 3. The callback function receives two parameters resolved Rejected
        // 4. Async operation successfully Execute resolved(value) Execute Rejected (reason)
        const p = new Promise((resolved, rejected) = >{
            setTimeout(() = >{
                // Emulate asynchronous tasks that succeed if the current time is even or fail otherwise
                const time = Date.now()
                time % 2= =0 
                ? resolved('Execution successful${time}`)
                : rejected('Execution failed${time}`)},1000)
        })

        p.then(
            // Successfully receive value data onResoled
            value= > {
                console.log(`onResoled ${value}`)},// Accept the failed Reason data onRejected
            reason= > {
                console.log(`onRejected ${reason}`)})Copy the code
Why use Promise
  • The way callback functions are specified is more flexible
    • Pure callback functions must be specified before starting asynchronous tasks
    • Promises can be specified after an asynchronous task is started
  • Support for chain calls to solve the callback hell problem
    • Callback functions are nested calls

conclusion

  • I promise to keep you updated