手写promise
-
Promise 的作用:解决 异步 回调地狱的问题;
即将异步 回调函数 作为 参数的嵌套写法,改为 .then 的 链式写法。 -
Promise 的写法:
const p = new Promise((resolve, reject) => {
resolve 和 reject 都是 函数执行 resolve(‘成功的数据’) ,成功的数据会被 p.then(res => res ) 获取
执行 reject(‘失败的数据’),失败的数据会被 p.catch(err => err) 获取
})
const oP = new Promise((resolve, reject) => {
// Q1:.then中的回调函数,什么时候 执行?
// 执行 resolve() 函数,立即执行 .then 中的回调函数。
// 补充:若 resolve 有实参,那么 实参会作为 .then 的回调函数的 实参值。
// Q2: .catch 中的回调函数,什么时候 执行?
// 执行 reject() 函数,立即执行 .catch 中的 回调函数。
// 补充1:若 reject 有实参,那么 实参会作为 .catch 的回调函数的 实参值。
// 补充2:若 本函数执行了 reject 函数,而 实例对象没有 catch 的实例方法,则 会 报错。
// Q3:resolve 和 reject,能 都执行吗?
// A:resolve 和 reject 两者,只能执行其一。
setTimeout(() => {
resolve('resolve-then');
}, 2000);
});
oP.then((res) => {
console.log('then中的回调函数执行', res);
})
.catch((err) => {
console.log('catch中的回调函数执行', err);
})
.finally(() => {
console.log('finally');
});
总结:
- Promise 构造函数的唯一参数,是函数:
1)本函数,立即执行
2)函数内部可能发生 异步代码
3)本函数内部,有三种状态,分别是:
1- pending:表示 既无 resolve执行,又无 reject 执行。
2- fulfilled:表示 执行了 resolve函数,实例对象会走 .then
3- rejected:表示 执行了 reject函数,实例对象会走 .catch
4)函数内部的状态只会由 pending -> fulfilled,或 pending -> rejected
// 上述两个过程,一旦发生,就此结束;!!不可逆!!- Promise 的实例对象,有三个实例方法:
1)oP.then(callback)
2)oP.catch(catchCallback)
3)oP.finally(finallyCallback)- oP
.then(res => {
return xxx
})
.then(res2 => {
// 注: res2 的值是 xxx
})
// 上 一个 .then 回调函数的返回值,可以作为 下一个 .then 回调函数的接收值。
// 注:返回值既可以是 普通数据,又可以是 Promise 的实例对象