0. Tease

1. What is promise?

Promise is a new asynchronous programming solution in ES6 and is represented in code as an object

2. Promise

  • Enterprise development for preservationThe execution order of asynchronous code, then it will appearThe callback functions are nested in layers
  • If there are too many nested layers of callback functions, the code becomes much less readable and maintainable
  • Promise objects can represent asynchronous operations as synchronous flows, avoiding layers of nested callback functions (callback hell)

Such as:

Requirements: Load three resources from the network. Resource 2 and resource 3 must be loaded only after resource 1 and resource 2 are loaded. If any of the preceding resources fail to be loaded, the subsequent resources will not be loaded

    function request(fn) {
        setTimeout(function () {
            fn("The data we got.");
        }, 1000);
    }
    request(function (data) {
        console.log(data, 1);
        request(function (data) {
            console.log(data, 2);
            request(function (data) {
                console.log(data, 3);
            });
        });
    });
    // The callback function is nested layer by layer
Copy the code

The use of promise

    function request() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve("The data we got.");
            }, 1000);
        });
    }
    request().then(function (data) {
        console.log(data, 1);
        return request();
    }).then(function (data) {
        console.log(data, 2);
        return request();
    }).then(function (data) {
        console.log(data, 3);
    });
Copy the code

1. Basic Concepts

1. What is Promise?

Promise is a new object in ES6 that allows you to use synchronous flows to represent asynchronous operations and avoid the problem of nested layers of callback functions (callback hell)

2. How do I create Promise objects?

new Promise(function(resolve, reject){});
Copy the code

Promise objects are not asynchronous, and the stored code executes as soon as a Promise object is created

3. How does Promise implement synchronous flow to represent asynchronous actions?

Promise objects are implemented through state changes that automatically trigger corresponding functions

4. There are three states of Promise objects

  • pending: The default state, as long as the promise is not told whether the task succeeds or fails, is pending
  • fulfilled(resolved): As long as the resolve function is called, the state will become depressing, indicating that the operation is successful
  • rejected: When the Rejected function is called, the status changes to Rejected, indicating that the operation fails
  • Note:Once the state is changed, it is not reversibleOnce it changes from pending to fulfilled, then it will always be fulfilled. Once it changes from pending to fulfilled, then it will always be fulfilled

5. Listen for Promise state changes

We can also use functions to listen for changes in state

  • resolved –> then()
  • rejected –> catch()

2. Promise-then method

1. The then method takes two arguments

  • The first parameter is thetaWhen the status changes to SucceededThe callback
  • The second parameter isWhen the status changes to failedThe callback
        let promise = new Promise((resolve, reject) = >{
            // resolve() // change the status to success, execute the successful callback
            reject() // Change the state to failed and execute the failed callback
        })
        promise.then(function(){
            console.log('Callback on success');
        },function(){
            console.log('Callback on failure');
        })
Copy the code

2. When modifying the Promise state, you can pass parameters to successful callbacks in the THEN method

        let promise = new Promise((resolve, reject) = >{
            // resolve() // change the status to success, execute the successful callback
            reject('123') // Change the state to failed and execute the failed callback
        })
        promise.then(function(){
            console.log('Callback on success');
        },function(res){
            console.log('Callback on failure', res);
        })
Copy the code

= = = = = = = = = >

        function success(){
            console.log('success123');
        }
        function error(data){
            console.log('error',data);
        }
        let promise = new Promise((resolve, reject) = >{
            // resolve() // change the status to success, execute the successful callback
            reject('123') // Change the state to failed and execute the failed callback
        })
        promise.then(success, error)
Copy the code

3. The same Promise object can call the then method multiple times, when the state of the promise objectallThen methods are executed

        let promise = new Promise((resolve, reject) = >{
            // resolve() // change the status to success, execute the successful callback
            reject('123') // Change the state to failed and execute the failed callback
        })
        promise.then(function(){
            console.log('Callback 1 on success');
        },function(res){
            console.log('Callback 1 on failure', res);
        })
        promise.then(function(){
            console.log('Callback 2 on success');
        },function(res){
            console.log('Callback 2 on failure', res);
        })
Copy the code

4. The then method returns one after each executionNew Promise object

        let promise = new Promise((resolve, reject) = >{
            // resolve() // change the status to success, execute the successful callback
            reject('123') // Change the state to failed and execute the failed callback
        })
        let p2 = promise.then(function(){
            console.log('Callback 1 on success');
        },function(res){
            console.log('Callback 1 on failure', res);
        })
        console.log(p2); / / promise object
        console.log(p2 === promise); // false
Copy the code

5. You can pass parameters to the then method of the next promise object through the then method of the previous promise object

Note: Arguments passed to either the successful or failed callback of the previous Promise object are passed to the successful callback of the next Promise object

        let promise = new Promise((resolve, reject) = > {
            // resolve() // change the status to success, execute the successful callback
            reject('123') // Change the state to failed and execute the failed callback
        })
        let p2 = promise.then(function (res) {
            console.log('Callback 1 on success', res);
            return '123'
        }, function (res) {
            console.log('Callback 1 on failure', res);
            return 'bbb'
        })
        p2.then(function (res) {
            console.log('Callback 2 on success', res);
        }, function (res) {
            console.log('Callback 2 on failure', res);
        })
Copy the code

The promise returned by the then method can receive arguments to the then method return in promise.then

6. If the then method returns aPromise object, will return the Promise objectValues in the result of executionPassed to theThe nextThen method

        let promise = new Promise((resolve, reject) = >{
            resolve('1')})let ppp = new Promise((resolve, reject) = >{
            reject('ppp')})let p1 = promise.then(function(data){
            console.log('1' success, data);
            return ppp
        },function(data){
            console.log(Failed to '1', data);
        })
        p1.then(function(data){
            console.log('2' success, data);
        },function(data){
            console.log('2' failure, data);
        })
Copy the code

3. Promise-catch method

1.catchIs actuallythen(undefined, () => {})Syntax sugar, there is no successful callback, only failed callback

	let promise = new Promise(function (resolve, reject) {
        // resolve(); // Change the status to succeeded
        reject(); // Change the status to failed
    });
    promise.catch(function () {
        console.log("abc");
    });
Copy the code

2. Separate monitor using chain programming

If separate listening is required, then listening succeeds and catch listening fails

You must use ** chained programming, otherwise an error will be reported **Copy the code
	let promise = new Promise((resolve, reject) = >{
            reject()
        })
        promise.then(function(){
            console.log('1' success);
        })
        promise.catch(function(){
            console.log('err');
        }) // Can listen to the failure, but will report an error
Copy the code

= = = = = modify = = = = = >

	promise.then(function(){
            console.log('1' success);
        }).catch(function(){
            console.log('err');
        })
Copy the code

2.1 The reason for using chain programming is as follows

  • 1. If the promise status isfailure, but an error is reported if there is no corresponding failed listener
  • 2. The then method returns oneThe new promise“The new promise willinheritanceThe original promise state
  • 3. If the new promise state isfailure, butThere is noThe correspondingFailed listeningWill also beAn error
    let promise = new Promise(function (resolve, reject) {
        // resolve(); // Change the status to succeeded
        reject(); // Change the status to failed
    });
    let p2 = promise.then(function () {
        console.log("Success");
    });
    console.log(p2);
    promise.catch(function () {
        console.log("Failure 1");
    });
    // P2 The new PROMISE state inherits the original promise state. The state is failed
    p2.catch(function () {
        console.log("Failure 2");
    });
Copy the code

3. As with THEN, when modifying the Promise state, you can pass parameters to the callback function in the catch method

	let promise = new Promise((resolve, reject) = >{
            reject('Failed.')
        })
        promise.catch(function(data){
            console.log(data); // Failed
        })
Copy the code

4. As with THEN, the same Promise object can be called multiple times when changing the state of the promise objectallCatch methods are executed

	let promise = new Promise((resolve, reject) = > {
            reject()
        })
        promise.catch(function () {
            console.log(Failed to '1');
        })
        promise.catch(function () {
            console.log('2' failure);
        })
        promise.catch(function () {
            console.log('3' failure);
        })
        /** Result failed 1 Failed 2 Failed 3 */
Copy the code

5. Same as then, catch each timeAfter executionWill return aNew Promise object

	let promise = new Promise((resolve, reject) = > {
            reject()
        })
        let p1 = promise.catch(function () {
            console.log(Failed to '1');
        })
        console.log(p1);
        console.log(p1 === promise);
Copy the code

6. As with the then method,The previous promise objectCan also giveThe next one promises successPassing parameters

Note: Arguments passed to either the successful or failed callback of the previous Promise object are passed to the successful callback of the next Promise object

    let promise = new Promise(function (resolve, reject) {
        reject();
    });
    let p2 = promise.catch(function () {
        console.log("Failure 1");
        return "it666";
    });
    p2.then(function (data) {
        console.log("Successful 2", data);
    }, function (data) {
        console.log("Failure 2", data);
    });
    /* Result: Failed 1 Succeeded 2, IT666 */
Copy the code

7. As with then, if the catch method returns aPromise object, will return the Promise objectThe execution resultIs passed to the next catch method

	let promise = new Promise(function (resolve, reject) {
            reject();
        });
        let ppp = new Promise(function (resolve, reject) {
            // resolve("1111");
            reject("abcd");
        });
        let p2 = promise.catch(function () {
            console.log("Failure 1");
            return ppp;
        });
        p2.then(function (data) {
            console.log("Successful 2", data);
        }, function (data) {
            console.log("Failure 2", data);
        });
        /* Result: Failed 1 Failed 2 abcd */
Copy the code

8. The difference between the catch method and the then method is that the catch method cancaptureIn the then method of the previous Promise objectabnormal

Then method

	let promise = new Promise(function (resolve, reject) {
            resolve();
        });
        promise.then(function () {
            console.log("Success");
            xxx
        }, function () {
            console.log("Failure");
        });
Copy the code

Catch method:

	let promise = new Promise(function (resolve, reject) {
            resolve();
        });
        promise.then(function () {
            console.log("Success");
            xxx
        }).catch(function (e) {
            console.log("Failure", e);
        });
Copy the code


Sunday (^_-)