JavaScript ES6 promiss的理解。

來源:互聯網
上載者:User

標籤:define   eject   個數   console   參數   同步   cti   rac   錯誤   

本著互連網的分享精神,我將我對promise的理解分享給大家。 

JavaScript ES6的promise方法主要應用在處理非同步函數返回的結果,注意他不是將非同步函數轉換為同步函數,而是等非同步函數有結果時在調用相應的方法進行處理。

promise有以下方法

  then() - 它最多需要有兩個參數,第一個是成功後調用的方法,第二個是失敗後調用的方法。

  catch() - 失敗後調用的方法,他與then方法的失敗後調用的方法類似,但是使用上有些區別,等下我會用案例講解。

  all() - 接收一個數組作為參數,數組內可填寫非同步函數,當所有的非同步函數都執行完後,會返回一個promise執行後的數組。但是有一點需要注意的是,入過參數內有一個方法報錯那麼他就會報錯,並不會返回結果。

  race() - 他與all的方法類似也接受一個數組作為參數(也是如如果數組內有一個方法報錯那麼他將會報錯,不會返回結果),但是有一點不同的是只返回一個結果,那就是哪個哪個函數最先執行完成返回的哪個結果。

  resolve() - 和then的第一個參數一樣,返回一個promise成功後調用方法。

  reject() - 和then的第二個參數一樣,返回一個promise失敗後調用的方法。

萬惡的非同步套回調。

本案例中我使用定時器類比ajax伺服器非同步請求。

function Fun(a, b, cb) {    setTimeout(function () {        cb(a + b)    }, 1000)}Fun(1, 2 ,function (result) {    console.log(result)});console.log(5); // 此時會先輸出5在輸出3

在複雜一點的案例肯定是回調套回調,這樣做肯定是沒有錯代碼也會執行,但是邏輯上不是很清晰。

function Fun(a, b, cb) {    setTimeout(function () {        cb(a + b)    }, 1000)}Fun(1, 2, function (result) {    if (result > 1) {        Fun(result, 2, function (result) {            Fun(result, 3, function (result) {                console.log(‘完成‘, result)            })        })    }});console.log(5); // 此時會先輸出5在輸出  完成 8
 使用promise方法重寫上面的案例- then的使用
function Fun(a, b) {    return new Promise(function (resolve, reject) {        setTimeout(function () {            resolve(a + b)        }, 1000)    })}Fun(1, 2)    .then(function (result) {        if (result > 1) {            return Fun(result, 2)        }    })    .then(function (result) {        if (result > 1) {            return Fun(result, 3)        }    }).then(function (result) {    console.log(‘完成‘, result)});
使用then方法處理錯誤失敗

then的第一個參數是處理Promise成功後使用的方法,第二個參數是Promise處理失敗後的方法,下面的案例我將會類比錯誤。

如果Fun函數內傳入的參數不是number類型,則觸發then方法的錯誤處理函數,也就是第二個函數,當然第一個函數就不會執行了。

function Fun(a, b) {    return new Promise(function (resolve, reject) {        if (typeof a !== ‘number‘ || typeof b !== ‘number‘) {            reject(new Error(‘no number‘))        }        setTimeout(function () {            resolve(a + b)        }, 1000)    })}Fun(1, ‘1‘)    .then(function (result) {        if (result > 1) {            return Fun(result, 2)        }    }, function (err) {    //這個方法將會被執行,因為報錯了麼,很好理解吧        console.log(err )    })    .then(function (result) {        console.log(‘第二個then‘); //輸出 第二個then 如果第一個then中的錯誤方法運用的妥當,對這裡是不會有影響的,但是我並沒有做相應的處理 只是輸出了err, result返回的是undefined,if中的方法也就不會執行了。        if (result > 1) {            return Fun(result, 3)        }    });

 

 使用 catch捕獲錯誤 - catch方法的使用

then方法是從上向下運行,啟動並執行中如果有發生錯誤的那麼then方法就會在發生錯誤哪裡停止運行,並且調用錯誤方法。注意:他與then的方法不同,then的處理機制處理完會繼續向下執行,而catch卻不會,會跳過未執行的then直接進入catch

function Fun(a, b) {    return new Promise(function (resolve, reject) {        if (typeof a !== ‘number‘ || typeof b !== ‘number‘) {            reject(new Error(‘no number‘))        }        setTimeout(function () {            resolve(a + b)        }, 1000)    })}Fun(1, 1)    .then(function (result) {        if (result > 1) {            console.log(1)  // 1正常輸出。            return Fun(result, ‘2‘) //這裡2不是number類型.        }    })    .then(function (result) { // 由於上面傳入的參數不是number類型,這裡的then 就會調用錯誤處理,也就是說會執行catch方法。
     console.log(2) // 不會執行 if (result > 1) { return Fun(result, 3) } }) .then(function (result) {
     console.log(3) // 不會執行 console.log(‘完成‘, result) }) .catch( function (err) { console.log(err) } );
如果使用catch和then的第二個參數同時捕獲參數會怎麼樣呢?

如果then方法有第二個參數那麼catch就不會執行,就會執行自己的第二個參數。可以將catch理解為接盤俠,如果then沒有處理錯誤的方法,那麼catch內的方法就會執行,如果同時沒有then的第二個方法和catch那麼就不會報錯,因為壓根就沒有錯誤的處理機制那麼就不會報錯了。

function Fun(a, b) {    return new Promise(function (resolve, reject) {        if (typeof a !== ‘number‘ || typeof b !== ‘number‘) {            reject(new Error(‘no number‘))        }        setTimeout(function () {            resolve(a + b)        }, 1000)    })}Fun(1, ‘1‘)    .then(function (result) {        if (result > 1) {            return Fun(result, 2)        }    }, function (err) {   //執行 輸出 no number +12        console.log(err + ‘12‘)       })    .then(function (result) {        console.log(‘第二個then‘); // 執行輸出 第二個then          if (result > 1) {  //這裡不會執行因為沒有result 因為result 是undefined 如果在第一個then的處理方法內處理的妥當這裡就可以執行。            return Fun(result, 3)        }    })    .catch(function (err) {  //這裡不會執行,因為每個then有自己的處理方式,所以catch就不會執行。        console.log(err + ‘我是catch的錯誤處理‘)    });

 

JavaScript ES6 promiss的理解。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.