Detailed explanation of Promise function

Detailed explanation of Promise function

The Javascript execution environment is single-threaded, which means that there is only one thread responsible for interpretation and execution in the JS environment, and only one task can be completed at a time. Callback.

Promise is a solution to asynchronous programming , to solve the problem of geographical callbacks, which is more reasonable and powerful than traditional solutions - callback functions and events.

Promise is a constructor. The Promise instance object created by new represents an asynchronous operation. It has all, reject, and resolve methods, and the prototype has methods such as then and catch.

Promise state

There are three states of the Promise object, which are pending (in progress), fulfilled (completed), and rejected (failed). Once a Promise object enters a certain state, it will not change to another state (mainly the latter two states, fulfilled and rejected). For example, once the resolve function is called, it is in the fulfilled state, and the reject function will not be called again.

pending: Waiting state, such as a network request is in progress, or the timer has not expired.

fulfilled: successfully, when we call back the resolve function, it is in this state.

rejected: to fail, when we call back the reject function, it is in this state.

Notes on .then and .catch functions:

The .then() function and .catch() both require a Promise object to be called. When using these two functions, the points to be noted are as follows:

1. When calling the .then() method, the successful callback function is mandatory, and the failed callback function is optional. That is, the parameters can be .then(resolve=>{},reject=>{}) or .then(resolve=>{}).

2. The resolve function returns a Promise object, even if return 'bbb' is used; such an explicit return will eventually be converted into a Promise object and returned. Returns can also be manually specified explicitly, as shown below. The newly returned Promise object can follow the then function again, and keep following it. If there is no return statement, the parameter of the returned object is undefined by default, that is, res is undefined.

p.then(res => {
    
    
    console.log('11-' + res);
    return 'AAA'; // 相当于Promise.resolve("AAA")
}).then(res => {
    
    
    console.log('22-' + res);
    return new Promise((resolve, reject) => {
    
    
        resolve(res); // 此处还可以调用reject
    })
}).then(res => {
    
    
    return Promise.resolve(res);
})

3. Reject returns empty, or no return. Because there is no return, it is meaningless to follow the then or catch function, and it will not be executed.

let newPromise = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        reject('BBB');
    }, 1000);
});
newPromise.then(null, error => {
    
    
    console.log("then:" + error);
}).catch(error => {
    
     // 这里的代码无意义,没有被执行
    console.log("catch:" + error); 
})

4. Call the Promise.then() function multiple times, the principle is the same. The data passed in is always the data of the calling object.

let newPromise = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve('BBB');
    }, 1000);
});
newPromise.then(res => {
    
    
    console.log("1:", res); // 输出 1:BBB
    return "ccc"
});
newPromise.then(res => {
    
    
    console.log("2:", res); // 输出 2: BBB,而不是 2: ccc
});
newPromise.then(null, error => {
    
    
    console.log("3:", error); // 不会执行,因为是已完成状态
});
let newPromise = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        reject('BBB');
    }, 1000);
}); 
newPromise.then(null, error => {
    
    
    console.log("4:", error); // 4: BBB
});
newPromise.catch(error => {
    
    
    console.log("5:", error); // 5:BBB
})

5. catch function. This function has two functions, one is equivalent to then(null,reject=>{}); the other is to catch the exception in resolve. If you don't want the previous error to cause the subsequent .then to fail to execute normally, you can call the .catch earlier.

let newPromise = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve('BBB');
    }, 1000);
});
newPromise.then(res => {
    
    
    console.log("6:", res);
    throw new Error('newError') // 6: BBB 
}).catch(error => {
    
    
    console.log("7:", error); // 7: Error: newError,捕获resolve中的异常
});

Promise.all(): waiting mechanism

Promise.all()The method will initiate parallel Promise asynchronous operations, and the next .then operation will be executed after all asynchronous operations are completed and the execution results are successful (waiting mechanism)

Promise.all([
    new Promise((resolve, reject) => {
    
    
        console.log("准备付钱");
        setTimeout(() => {
    
    
            console.log("支付成功");
            resolve("Pay Success")
        }, 2000);
    }),
    new Promise((resolve, reject) => {
    
    
        console.log("商家发货");
        setTimeout(() => {
    
    
            console.log("收到货物");
            resolve("Send Success")
        }, 1000);
    })
]).then(result => {
    
    
    console.log("交易完成");
    console.log(result);
})

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-MB5nX6K4-1678069645529) (C:\Users\zhaoyue\AppData\Roaming\Typora\typora-user-images\ 1678016054870.png)]

Promise.race(): race mechanism

Promise.race()The method will initiate parallel Promise asynchronous operations, and as soon as any asynchronous operation is completed , the next .then operation will be executed immediately (race mechanism).

Promise.race([
    new Promise((resolve, reject) => {
    
    
        console.log("准备付钱");
        setTimeout(() => {
    
    
            console.log("支付成功");
            resolve("Pay Success")
        }, 1000);
    }),
    new Promise((resolve, reject) => {
    
    
        console.log("商家发货");
        setTimeout(() => {
    
    
            console.log("收到货物失败");
            reject("Send Failure");
        }, 2000);
    })
]).then(res => {
    
    
    console.log("success":res);
}).catch(error => {
    
    
    console.log("error":error);
})

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-gb3xtY7O-1678069645531) (C:\Users\zhaoyue\AppData\Roaming\Typora\typora-user-images\ 1678016332270.png)]

Guess you like

Origin blog.csdn.net/weixin_54026054/article/details/129356378