js 深入原理讲解系列-Promise
能看懂这一题你就掌握了 js Promise 的核心原理
不要专业的术语,说人话,讲明白!
Q: 输出下面 console.log 的正确的顺序?
const log = console.log;
A:
Promise
不可逆状态: pending => fullfilled, pending => rejected
Promise.resolve()
Promise.reject()
executor 执行器
thenable 包含 then 的对象,会立即执行 then ?
then
Promise.all
Promise.allSettled
Promise.any
Promise.race
Promise.catch 语法糖 new Promise(null, (err) => reject(err))
Promise.finally 兜底
Promise.try ❓too new for now
try...catch
Promise
let promise = new Promise((resolve, reject) => resolve(`value`));
// let promise = new Promise((resolve, reject) => reject(`error`));
promise.then(function(value) {
// success, fullfiled ✅ / (resolved ❌)
console.log(`OK =`, value);
}, function(error) {
// failure, rejected
console.log(`Error =`, error);
});
// OK = value
promise = new Promise((resolve, reject) => {
throw new Error(`promise error!`);
});
promise.then(function(value) {
// success, fullfiled ✅ / (resolved ❌)
console.log(`OK =`, value);
}, function(error) {
// failure, rejected
console.log(`Error =`, error);
}).catch(err => {
console.log(`Catch Error =`, err);
});
// Error = Error: promise error!
thenable
const log = console.log;
const thenableOK = {
then: function(resolve, reject) {
log(`thenable ✅`);
resolve(2020);
},
};
Promise.resolve(thenableOK).then(function(value) {
log(`value =`, value);
// 2020
}, function(error) {
log(`error =`, error);
});
// thenable ✅
// value = 2020
// Promise {<fulfilled>: undefined}
const thenableError = {
then: function(resolve, reject) {
log(`thenable ❌`);
reject(2020);
}
};
Promise.resolve(thenableError).then(function(value) {
log(`value =`, value);
}, function(error) {
log(`error =`, error);
});
// thenable
// error = 2020
// Promise {<fulfilled>: undefined}
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!