ES6 learning notes (Promise)

The Promise object is used to represent the final state (completion or failure) of an asynchronous operation and the value it returns.

1. callbacks

If Promise is not used, multiple layers of nesting are needed in the layer-by-layer call of functions, so it will take a lot of work to modify the code when the requirements change. However, with Promise, the code can be arranged into a chain structure through the keywords of then. If you want to modify the nested logic, you only need to modify the order of then.

function f() {
    return new Promise(resolve => {
        setTimeout(function () {
            resolve();
        },1000);
    })
}
f()
    .then(function () {
        console.log(1);
        return f();
    })
    .then(function () {
        console.log(2);
        return f();
    })
    .then(function () {
        console.log(3);
        return f();
    })
    .then(function () {
        console.log(4);
        return f();  //If you want to print3and4Only need to modifythenOrder of post methods
    });

2. Error handling

resolve,reject

If successful, execute the resolve method, if unsuccessful, execute the reject method

function f(val) {
    return new Promise((resolve,reject) => {
        if (val){
            resolve();
        } else {
            reject();
        }
    })
}

f(false)
    .then(() => {
        console.log('Success!');
        },() => {
        console.log('Failure!');
    });
Catch catch exception

In case of return failure, the following functions will not be executed again, only the catch method can catch exceptions

function f(val) {
    return new Promise((resolve,reject) => {
        if (val){
            resolve();
        } else {
            reject();
        }
    })
}

f(true)
    .then(() => {
        console.log('Success!');
        return f(false)
        })
    .then(() => {
        console.log("Never output");
    })
    .catch(() =>{
        console.log("fail!");
    });
finally

No matter the previous function succeeds or fails, finally will be executed

function f(val) {
    return new Promise((resolve,reject) => {
        if (val){
            resolve();
        } else {
            reject();
        }
    })
}

f(true)
    .then(() => {
        console.log('Success!');
        return f(false)
        })
    .then(() => {
        console.log("Never output");
    })
    .catch(() =>{
        console.log("fail!");
    })
    .finally(() =>{
        console.log("It will be executed!");
    });

Added by Rony on Sun, 05 Jan 2020 20:38:05 +0200