阿里面试题:
手动封装promise函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/*
*Promise实现思路
* 1.构造函数
* 2.回调函数的参数 resolve reject
* 3.链式调用.then .catch
*/ function PromiseM(cb){
//初始状态
this.status = "pending";
this.msg = ""; cb((data)=>{
this.status = "resolve";
this.msg = data;
},()=>{
this.status = "reject";
})
return this;
} //链式调用.then
PromiseM.prototype.then = function(){
var cb = arguments; //轮询实现异步
timer = setInterval(()=>{
if(this.status == "resolve"){
//成功状态的回调
cb[0](this.msg);
clearInterval(timer);
}else if(this.status == "reject"){
//失败状态的回调
cb[1](this.msg);
clearInterval(timer);
}
},3000)
} new PromiseM(function (resolve,reject){
setTimeout(function (){
console.log(1111);
resolve('11111');/*reject也就是失败时对应的函数,由于这个例子比较简单*/
},1000)
}).then(function (data){
console.log("接收的值为"+data);
}) </script>
</body>
</html>