關於js中promise的面試題。

核心點
promise在生命週期內有三種狀態,分別是pending,fulfilled或rejected,狀體改變只能是 pending-fulfilled,或者pending-rejected。並且狀態一旦改變就不能再次改變。promise

題1函數

promise.resolve().then(() => {
         console.log('a');
         return new Error('error');
     })
     .then((res)=>{
         console.log('b');
         console.log('then:',res);
     })
     .catch((err) =>{
         console.log('c');
         console.log('catch:',err);
     })

可能有些同窗會認爲出現了 new Error()就會想固然的認爲會執行後面的catch函數,其實否則。code

在then函數中return了一個Error,依然會按照正常的流程走下去,並不會執行後續的catch函數,這個是不一樣於thorw拋出一個Error的,若是是throw拋出一個Error則會被catch函數捕獲。生命週期

因次答案是:io

a
b
c
then:Error : error

題2console

const promise = Promise.resolve()
                       .then(()=>{
                           return promise;
                       });
       promise.catch(console.error);

結果是function

TypeError:Chaining cycle detected for promise #<Promise>

咱們須要知道的是Promise的then或者catch裏不能返回promise自己,不然會出現死循環,就是上面報的錯誤。循環

題3方法

Promise.resolve(1)
       .then(2)
       .then(Promise.resolve(3))
       .then(console.log);

這個題目主要考察的是在 Promise的then或者catch方法中,接收的是一個函數,函數的參數是resolve或者rejiect函數的返回值,若是傳入的值是非函數,那麼就會產生值的穿透現象。
何爲值穿透現象,簡單理解就是傳遞的值會被直接忽略掉,繼續執行鏈調用後續的方法。
因此 題3的 答案是 1.
第一個then接受值2 ,第二個接收一個Promise,都不是須要的函數,所以這二個then會發生值穿透。
而第三個then由於接收console.log函數,所以會執行,此時接收的是最開始的resolve(1)的值,所以最後返回 1.error

題4

Promise.resolve()
       .then(function success(res){
           throw new Error('error');
       },function faill(e){
           console.error('fail1:',e);
       })
       .catch(function fail2(e){
           console.error('fail2',e);
       })

在Promise的then方法中,能夠接收兩個函數,一個是用於resolve成功的函數,一個是用於reject失敗的函數,兩個函數只會調用一個。咱們還能夠經過.catch方法去實現then方法中的第二個表示失敗的函數。

可是有一點不一樣的是.catch方法能夠捕獲以前從then方法中拋出的Error,而then方法中的第二個方法捕獲不到第一個處理成功的方法中拋出的Error。

所以咱們能夠得出這道題目的答案,拋出fail2的Error。

上述的題目能夠用下面的代碼去理解

Promise.resolve()
    .then(function success1 (res){
        thorw new Error('error');
    },function() fail1(e){
        console.error('fail1',e);
    })
    .then(function success2(res){},function fail2(e){
        console.error('fail2:',e);
    })
相關文章
相關標籤/搜索