Promise
Promise 是将“生产者代码”和“消费者代码”连接在一起的特殊对象
js
typeof new Promise(() => {}); // 'object'
Object.prototype.toString.call(Promise.resolve(1)); // '[object Promise]'js
let promise = new Promise(function (resolve, reject) {});promise 的 state 只能
"pending" 变为 "fulfilled"
或 "pending" 变为 "rejected"
Promise 对象的 state 和 result 属性都是内部的,无法访问。
一个 Promise 只能有一个结果。
消费
js
promise.then(
function (result) {
/* handle a successful result */
},
function (error) {
/* handle an error */
}
);或
js
promise
.then(function (result) {
/* handle a successful result */
})
.catch(function (error) {
/* handle an error */
});清理:finally
finally 处理程序(handler)没有参数。
finally 不应该返回任何内容,返回了也会被忽略。
finally 无法处理结果,所以原本的结果会传递下去。
js
Promise.resolve(1)
.finally(() => {})
.then((val) => console.log(val)); // 1Promise 链
每一个 then,都返回一个新的 Promise(Thenables)
“thenable” 对象 —— 一个具有方法 .then 的任意对象。它会被当做一个 promise 来对待。
js
class Thenable {
constructor(num) {
this.num = num;
}
then(resolve, reject) {
alert(resolve); // function() { native code }
setTimeout(() => resolve(this.num * 2), 1000); // (**)
}
}错误
一个 .catch 可以捕获多个 .then 的 error。
js
fetch("/article/promise-chaining/user.json")
.then((response) => response.json())
.then((user) => fetch(`https://api.github.com/users/${user.name}`))
.then((response) => response.json())
.catch((error) => alert(error.message));隐式 try…catch
js
new Promise((resolve, reject) => {
throw new Error("Whoops!");
}).catch(alert); // Error: Whoops!
// 二者相同
new Promise((resolve, reject) => {
reject(new Error("Whoops!"));
}).catch(alert); // Error: Whoops!未处理的 rejection 会产生一个全局 error
js
window.addEventListener("unhandledrejection", function (event) {
// 这个事件对象有两个特殊的属性:
alert(event.promise); // [object Promise] —— 生成该全局 error 的 promise
alert(event.reason); // Error: Whoops! —— 未处理的 error 对象
});async/await
async 函数总是返回一个 promise。他的值将自动被包装在一个 resolved 的 promise 中。
await 只能在 async function 中使用