Getting Started with Promise Basics

1. What problem does Promise use to solve?

1. What is an asynchronous program

  1. client
    • timer
    • ajax
  2. Server (Node.js)
    • fs file operation
    • database operation

2. What is asynchronous

setTimeout(function(){
    
    
  console.log("异步请求1");
}, Math.round(Math.random()*1000));

setTimeout(function(){
    
    
  console.log("异步请求2");
}, Math.round(Math.random()*1000));

setTimeout(function(){
    
    
  console.log("异步请求3");
}, Math.round(Math.random()*1000));

3. What is callback hell

  • The callback function is nested and called, and the inner asynchronous program is called according to the execution result of the outer asynchronous program
setTimeout(function(){
    
    
  console.log("异步程序1");

  setTimeout(function(){
    
    
    console.log("异步请求2");

    setTimeout(function(){
    
    
      console.log("异步请求3");
    }, Math.round(Math.random()*1000));

  }, Math.round(Math.random()*1000));

}, Math.round(Math.random()*1000));
  • Disadvantages of callback hell: low code readability, not conducive to error checking, and poor exception handling mechanism

3. Using Promise to optimize callback hell

  1. A simple explanation of Promise
  2. Optimizing Callback Hell Using Promises
    • The chain call of Promise can solve the callback hell problem very well
asyncFunc1().then(response => {
    
    
  return asyncFunc2();
}).then(response => {
    
    
  return asyncFunc3();
}).then(response => {
    
    
  // 所有异步完成后的其他操作
})
  1. Advantages of using Promise
    • easy to read
    • Easy to troubleshoot
    • state management

Second, the use of Promise

1. The basic state of Promise

  1. The meaning and characteristics of the three states
    1. pending: in progress...
    2. fulfilled: completed
    3. rejected: failed

2. The basic syntax of Promise

Create a Promise instance and immediately pass in the callback function

new Promise((resolve, reject)=>{
    
    
  console.log("正在进行时");
  resolve("已完成")
  reject("已失败")
})

3. Promise instance method

  1. promise.then()
    • Executed when the promise instance status is successful
    • Parameters: callback function; callback 1 is used to handle success status, callback 2 is used to handle failure status, callback 2 is optional
    • Return value: the return value of the callback function corresponding to the state of the current promise instance. This return value must be a new Promise instance, even if the returned one is not a Promise instance, it will be processed into a Promise instance
  2. promise.catch()
    • Executed when the promise instance status is failed
    • Parameters: callback function, used to handle failure status
    • Return value: the return value of the callback function
  3. promise.finally()
    • It will be executed when the promise instance status is successful or failed, indicating that the current promise is over
    • Parameters: callback function, used to process the state after completion
    • Return value: the return value of the callback function

4. Use the method of Promise instance to optimize the callback hell problem

  1. scene description
  2. Solution: chain callback
  3. Summarize

5. Promise class methods

  1. Promise.resolve()
    • Returns a Promise instance with success status
    • Parameters: data in success state
  2. Promise.reject()
    • Returns a Promise instance with a failed status
    • Parameters: data in failed state
  3. Promise.all()
    • Used to wrap multiple Promise instances into a new Promise instance.
    • Promise.all() is successful only if all sub-instances succeed, and fails as long as one sub-instance fails.
    • Parameters: Array of multiple Promise instances
  4. Promise.any()
    • Used to wrap multiple Promise instances into a new Promise instance.
    • Promise.any() succeeds as long as one sub-instance succeeds, and fails when all sub-instances fail.
    • Parameters: Array of multiple Promise instances
  5. Promise.race()
    • Used to wrap multiple Promise instances into a new Promise instance.
    • The Promise.race() race mechanism depends on the state of the child instance that finishes execution first
    • Parameters: Array of multiple Promise instances
  6. Promise.allSettled()
    • Used to wrap multiple Promise instances into a new Promise instance.
    • Promise.allSettled() all sub-instances end, the new instance will be completed, including the status of all sub-instances
    • Parameters: Array of multiple Promise instances

3. The ultimate asynchronous solution: Async / Await

  1. asyncThe keyword, functionused before the keyword of the function, is used to indicate that the current function is an asynchronous function, and the function execution result automatically returns an Promiseinstance of a successful state, and the keyword in this asynchronous function is used to return success returnto the instance of the successful state Promisetime data.
async function fn1(){
    
    }

console.log(fn1());		// Promise {<fulfilled>: undefined}

async function fn2(){
    
    
    return "hello";
}

console.log(fn2());		// Promise {<fulfilled>: 'hello'}

fn2().then(res=>{
    
    
    console.log(res);		// hello
})
  1. awaitThe keyword can only asyncbe used in the declared asynchronous function, which means wait. Data when waiting for an asynchronous execution to complete and return a success status. awaitAsynchronous functions can be executed synchronously, awaitgenerally used for waiting Promisestate
async function fn(){
    
    
    const res = await test();
    console.log(res);		// success 或 error
}

function test(){
    
    
    return new Promise((resolve, reject)=>{
    
    
        setTimeout(function(){
    
    
            resolve("success");
        },Math.random()*1000)
      
        setTimeout(function(){
    
    
            reject("error");
        },Math.random()*2000)
    })
}

Guess you like

Origin blog.csdn.net/weixin_41636483/article/details/127484315