挑戰前端基礎120題--JavaScript 中如何實現鏈式調用的函數?

一. 何爲鏈式調用?

鏈式調用是一種簡化過程的編碼方式,使代碼看起來更加簡潔~它允許你通過在方法調用之間返回對象本身,從而連續地調用多個方法;比較常見的鏈式調用:jQuery, Promise等,通過多次書寫.()操作來調用。

二. 實現的原理?

每次執行完成後返回自己/新的自己,這樣可以確保後續的方法仍然在當前環境下執行;

三. 如何實現?

let p = {
  then() {
     console.log('輸出-->then');
     return this;
  }
}
console.log(p.then().then());

 

function myPromise () {
    return this;
}
myPromise.prototype.then = function () {
    console.log('my promise');
    return new myPromise(); // this
}

let myP1 = new myPromise();
console.log(myP1.then().then().then())

 四. 深入理解下Promise鏈式調用的規則?

let pro = new Promise((resolve, reject) => {
    resolve('我是一個promise對象')
})
console.log(pro); // Promise
pro.then(res => {
    console.log(res); // 我是一個promise對象
}).then(res => {
    console.log(res);  // undefined
    return 123;
}).then(res => {
    console.log(res); // 123
    return new Promise(resolve => {
        resolve('456')
    })
}).then(res => {
    console.log(res); // 456
}).then(res => {
    console.log(res); //undefined
}).then(res => {
    console.log(res); // undefined
    return '我是直接返回的結果';
}).then()
    .then('我是字符串').
    then(function (res) {
    console.log(res); // 我是直接返回的結果
})

總結:

1. 只要有then() 並且觸發了resolve,鏈式就會執行到結尾,res 就是爲resolve參數傳入的值;

2. 每個函數也可以使用return返回值,沒有的話後續下一個then中回調函數的值默認undefined;

3. 返回值如果是一個普通值,則直接傳遞到下個then,如果是一個Promise對象,那麼此Promise對象的resolve傳入的值就會被當作後續下一個then中回調函數的值;

4. 如果then中傳入的值不是回調函數或者沒有傳遞值,鏈式調用並不是中斷,而是繼續往下執行,這是後面獲取到的res爲最後一次return/resolve傳入的值;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章