Promise-03 多个then调用
2020-09-11 本文已影响0人
呆桃冲鸭冲鸭
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>my</title>
</head>
<body>
<p>test my</p>
</body>
<script type="module">
// type="module" 严格模式
import MyPromise from './promise.js';
// 三种状态 1.pending 2.fulfilled 3.rejected
let myP = new MyPromise((resolve,reject)=>{
setTimeout(()=>{
console.log('====')
resolve("suc...");
});
// reject("err...");
});
// console.log(myP);
//then 2个参数 1.异步 2.同步
// 先执行了函数 后保存的函数
// myP.then(res=>{
// console.log(res);
// },err=>{
// console.log(err);
// });
// 多个then调用
myP.then(res=>{
console.log("1:",res);
},err=>{
console.log(err);
});
myP.then(res=>{
console.log("2:",res);
},err=>{
console.log(err);
});
</script>
</html>
promise.js:
export default class MyPromise{
constructor(handle){
this.state = "pending";
this.result = undefined;
this.resolveFnArr = [];
this.rejectFnArr = [];
handle(this._resolve.bind(this),this._reject.bind(this));
};
_resolve(val){
this.state = "fulfilled";
this.result = val;
// 执行then的回调
setTimeout(()=>{
let cb;
while(cb = this.resolveFnArr.shift()){
cb && cb(val);
};
},0);
};
_reject(val){
this.state = "rejected";
this.result = val;
// 执行then的回调
setTimeout(()=>{
let cb;
while(cb = this.rejectFnArr.shift()){
cb && cb(val);
};
},0);
};
then(onResolved,onRejected){
// 异步onResolved,onRejected不会立即执行;是在调取_resolve、_reject再执行
// 保存onResolved、onRejected
this.resolveFnArr.push(onResolved)
this.rejectFnArr.push(onRejected)
};
}
