Promise review and summary (review the past and learn the new)
Reference: https://juejin.cn/post/6844903604009041928
1.promise syntax
Promise
The core idea of programming is that if the data is ready ( promised
), then ( then
) do something.
promise instance
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
})
Promise
The constructor accepts a function as a parameter, and the two parameters of the function are resolve
and reject
.
resolve函数的作用是
, change the state of the Promise object from “未完成”变为“成功”
pending to resolved, call it when the asynchronous operation is successful, and pass the result of the asynchronous operation as a parameter;
reject
The function of the function is to change the state of the Promise object from “未完成”变为“失败”
pending to rejected, to be called when the asynchronous operation fails, and to pass the error reported by the asynchronous operation as a parameter.
After the Promise instance is generated, you can use the then method to specify the callback functions for the resolved state and rejected state respectively.
promise.then(function(value) {
// success
}, function(error) {
// failure
});
then
The method can accept two callback functions as parameters.