阿里面試題:html
手動封裝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>