Introduction and basic use of Promise

What is Promise

  • Simply put, Promise is a solution for asynchronous programming.

Why is there a promise?

First, let us know what is asynchronous and synchronous:

  • Synchronization: Suppose you go to a restaurant, find a location, and call the waiter. At this time, the waiter tells you, I'm sorry I am a "synchronization" waiter, and I have to finish serving this table before I can greet you. The guests at that table obviously have already eaten, you just want a menu, such a small action, but the waiter wants you to wait until someone else's big action is completed before they come to greet you again. This is a synchronization problem: that is, "order" The work delivered 1234 must be completed in the order of 1234".
  • Asynchronous: After handing over the time-consuming work delivered by A to the system, continue to do the work delivered by B. After the system has completed the previous work, it can continue to do the remaining work of A through callbacks or events.
    The order of completion of AB's work has nothing to do with the order of delivery of them, so it is called "asynchronous".

use

Promise: When making asynchronous requests,
Promise is an internally encapsulated class. Its constructor will be executed when new (1. Save some state information, 2. Execute the function we passed in).
When executing the incoming callback function, Will pass in two parameters, resolve and reject, which are themselves a function

  new Promise((resolve,reject)=>{
    
    
  //模拟异步请求
            setTimeout(() => {
    
    
                //执行成功时调用resolve
                resolve();
                //执行失败时调用reject
                reject();
            }, 3000);
        }).then(()=>{
    
    
            //执行resolve时会来到then
            console.log('hello');
        }).catch(()=>{
    
    
            //执行失败会来到catch
            console.log('error')
        })

Parameters can be passed when the asynchronous request succeeds or fails, which is equivalent to further processing the data obtained when making a network request

 new Promise((resolve,reject)=>{
    
    
            setTimeout(() => {
    
    
                //执行成功时调用resolve
                resolve('执行成功');//resolve中传入的参数对应到then中回调函数中的参数
            }, 3000);
        }).then((data)=>{
    
    
            //执行resolve时会来到then
            console.log(data);
        })

Guess you like

Origin blog.csdn.net/weixin_45925906/article/details/113104828