Introduction to the basic usage of ES6 Promise

Introduction to the basic usage of ES6 Promise

1. What is a promise?
Promise is a solution for asynchronous programming: the semantics is a promise, and a promise is an object, which can get the message of asynchronous operation; promise it will give you a result after a period of time. Promise has three states: pending (waiting state), fulfiled (successful state), rejected (failed state); once the state changes, it will not change. After the promise instance is created, it will be executed immediately.

Code demo:
Insert picture description here

2. Advantages of Promise
You may think that this is no different from writing a callback function; then, what if there are multiple callbacks? What if callback is also an asynchronous operation and needs a corresponding callback function after execution? You can never define a callback2, and then pass it in to the callback. The advantage of Promise is that you can continue to write and return the Promise object in the then method, and then continue to call then to perform the callback operation.

ajax()
.then(function(data){
    
    
    console.log(data);
    return Async1();
})
.then(function(data){
    
    
    console.log(data);
    return Async2();
})
.then(function(data){
    
    
    console.log(data);
    return Async3();
});

Guess you like

Origin blog.csdn.net/weixin_49092628/article/details/112433289