<!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)=>{
resolve("suc...");
// reject("err...");
});
//微任务
// myP.then(res=>{
// console.log("Promise=====222");
// },err=>{
// console.log(err);
// });
// then链式调用 三种返还值(不返还、返还普通的字符串或数字、返还promise对象)最终返还promise对象
let p = myP.then(res=>{
console.log(res)
// return 111;
return new MyPromise((resolve,reject)=>{
resolve("222...");
});
});
p.then(res=>{
console.log(res)
})
</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的回调 变成微任务执行
const run = () => {
let cb;
while(cb = this.resolveFnArr.shift()){
cb && cb(val);
};
};
const observer = new MutationObserver(run);
observer.observe(document.body,{attributes: true});
document.body.setAttribute("my",Math.random());
};
_reject(val){
this.state = "rejected";
this.result = val;
// 执行then的回调 变成微任务执行
const run = () => {
let cb;
while(cb = this.rejectFnArr.shift()){
cb && cb(val);
};
};
const observer = new MutationObserver(run);
observer.observe(document.body,{attributes: true});
document.body.setAttribute("my",Math.random());
};
then(onResolved,onRejected){
// 异步onResolved,onRejected不会立即执行;是在调取_resolve、_reject再执行
// 保存onResolved、onRejected
return new MyPromise((resolve,reject)=>{
let resolveFn = val => {
let res = onResolved && onResolved(val);
//判断是否是MyPromise对象
if(res instanceof MyPromise){
// return res.then((res)=>{
// resolve(res)
// })
return res.then(resolve)
}
resolve(res);
};
let rejectedFn = val => {
onRejected && onRejected(val);
reject(val);
};
this.resolveFnArr.push(resolveFn)
this.rejectFnArr.push(rejectedFn)
});
};
}
网友评论