ES7 之 Async/await 的使用(改進 Promise 鏈式操做)

在 js 異步請求數據時,一般,咱們多采用回調函數的方式解決,可是,若是有多個回調函數嵌套時,代碼顯得很不優雅,維護成本也相應較高。 ES6 提供的 Promise 方法和 ES7 提供的 Async/Await 語法糖能夠更好解決多層回調問題。html

Promise 對象用於表示一個異步操做的最終狀態(完成或失敗),以及其返回的值。
await 操做符用於等待一個Promise 對象。它只能在異步函數 async function 中使用。
await 表達式會暫停當前 async function 的執行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調的resolve函數參數做爲 await 表達式的值,繼續執行 async function。node

一個ajax請求時

一般 使用 ajax 請求數據時,會git

$.ajax({
    url: 'data1.json',
    type: 'GET',
    success: function (res) {
        console.log(res) // 請求成功,則獲得結果res
    },
    error: function(err) {
        console.log(err)
    }
})

上面能夠獲得咱們想要的結果 res ---> { "url": "data2.json" }es6

多個ajax請求時

可是 當獲得的數據 res 須要用於另外一個 ajax 請求時,則須要以下寫法:github

$.ajax({
    url: 'data1.json',
    type: 'GET',
    success: function (res) {
        $.ajax({
            url: res.url, // 將 第一個ajax請求成功獲得的res 用於第二個ajax請求
            type: 'GET',
            success: function (res) {
                $.ajax({
                    url: res.url,  // 將第二個ajax請求成功獲得的res 用於第三個ajax請求
                    type: 'GET',
                    success: function (res) {
                        console.log(res)   // {url: "this is data3.json"}
                    },
                    error: function(err) {
                        console.log(err)
                    }
                })
            },
            error: function(err) {
                console.log(err)
            }
        })
    },
    error: function(err) {
        console.log(err)
    }
})

上面出現多個回調函數的嵌套,可讀性較差(雖然這種嵌套在日常的開發中少見,可是在node服務端開發時,仍是很常見的)web

優化方法

使用 promise 鏈式操做

以下,使用 Promise,進行鏈式操做,可使上面的異步代碼看起來如同步般易讀,從回調地獄中解脫出來。。ajax

function ajaxGet (url) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: url,
            type: 'GET',
            success: function (res) {
                resolve(res);
            },
            error: function(err) {
                reject('請求失敗');
            }
        })
    })
};

ajaxGet('data1.json').then((d) => {
    console.log(d);       // {url: "data2.json"}
    return ajaxGet(d.url);
}).then((d) => {
    console.log(d);       // {url: "data3.json"}
    return ajaxGet(d.url);
}).then((d) => {
    console.log(d);       // {url: "this is data3.json"}
})

注意,promise 返回的仍然是 promise

下面兩種方式的等效的:json

1. 直接使用 promise

function ajaxPromiseGet(url) {
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: url,
                type: 'GET',
                success: function (res) {
                    resolve(res)
                },
                error: function (err) {
                    reject('請求失敗')
                }
            })
        })
    }

 
    ajaxPromiseGet(`/products/list/`).then(list => {
        if (list) {
            console.log(list)
        }
    })

2. 當須要先統一處理 promise 返回值時

function ajaxPromiseGet(url) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: url,
            type: 'GET',
            success: function (res) {
                resolve(res)
            },
            error: function (err) {
                reject('請求失敗')
            }
        })
    })
}

// 先統一處理 promise 
function handleList () {
    let ajaxReault = ajaxPromiseGet(`/products/list/`)
    return ajaxReault.then(list => {
        return list.filter(item => item.status == 0)
    })
}

handleList().then(list => {
    if (list) {
        console.log(list)
    }
})

Async/await 方法

  • async 表示這是一個async函數,即異步函數,await只能用在這個函數裏面。
  • await 表示在這裏等待promise返回結果了,再繼續執行。
  • await 後面跟着的應該是一個promise對象(固然,其餘返回值也不要緊,只是會當即執行,不過那樣就沒有意義了…)
  • await 操做符用於等待一個Promise 對象。它只能在異步函數 async function 中使用。
  • await 等待的雖然是promise對象,但沒必要寫.then(..),直接能夠獲得返回值。

執行一個ajax請求,能夠經過以下方法:promise

function ajaxGet (url) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: url,
            type: 'GET',
            success: function (res) {
                resolve(res)
            },
            error: function(err) {
                reject('請求失敗')
            }
        })
    })
};

async function getDate() {
    console.log('開始')
    let result1 = await ajaxGet('data1.json');
    console.log('result1 ---> ', result1); // result1 --->  {url: "data2.json"}
};

getDate();  // 須要執行異步函數

執行多個ajax請求時:異步

function ajaxGet (url) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: url,
            type: 'GET',
            success: function (res) {
                resolve(res)
            },
            error: function(err) {
                reject('請求失敗')
            }
        })
    })
};

async function getDate() {
    console.log('開始')
    let result1 = await ajaxGet('data1.json');
    let result2 = await ajaxGet(result1.url);
    let result3 = await ajaxGet(result2.url);
    console.log('result1 ---> ', result1); // result1 --->  {url: "data2.json"}
    console.log('result2 ---> ', result2); // result2 --->  {url: "data3.json"}
    console.log('result3 ---> ', result3); // result3 --->  {url: "this is data3.json"}
};

getDate();  // 須要執行異步函數

async await捕捉錯誤:

  • async await中.then(..)不用寫了,那麼.catch(..)也不用寫,能夠直接用標準的try catch語法捕捉錯誤。

例如,若是下面的 url 寫錯了

function ajaxGet (url) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: url111, // 此處爲錯誤的 url
            type: 'GET',
            success: function (res) {
                resolve(res)
            },
            error: function(err) {
                reject('請求失敗')
            }
        })
    })
};


async function getDate() {
    console.log('開始')
    try {
        let result1 = await ajaxGet('data1.json'); // 執行到這裏報錯,直接跳至下面 catch() 語句
        let result2 = await ajaxGet(result1.url);
        let result3 = await ajaxGet(result2.url);
        console.log('result1 ---> ', result1);
        console.log('result2 ---> ', result2);
        console.log('result3 ---> ', result3);

    } catch(err) {
        console.log(err) // ReferenceError: url111 is not defined
    }
};

getDate();  // 須要執行異步函數

源碼

源碼查看

更多

請參考:

相關文章
相關標籤/搜索