解決異步問題——promise

promise介紹

  • promise主要是為了解決嵌套回調(diào)的問題,使代碼更加簡潔,promise將嵌套的回調(diào)函數(shù)改成.then()的連綴使用

promise 的使用

  • 方法:

    • 首先通過new Promise(function)創(chuàng)建一個(gè)promise對(duì)象,接收一個(gè)函數(shù)參數(shù),并且在函數(shù)中傳入resolve以及reject兩個(gè)參數(shù);
var p = new Promise(function(resolve, reject){      
            //做一些異步操作
            setTimeout(function(){
                console.log('這是一個(gè)異步操作');
                resolve('異步操作成功并且結(jié)束');
            }, 1000);
        });

API

  • then() 接收兩個(gè)函數(shù),分別是對(duì)promise的resolve及reject狀態(tài)處理的函數(shù),并且處理結(jié)束之后返回promise對(duì)象
 function fn1() {
        console.log("第一個(gè)函數(shù)開始執(zhí)行");
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第一個(gè)函數(shù)執(zhí)行完畢');
                resolve('接下來進(jìn)入第二個(gè)函數(shù)');
            }, 1000);
        });
        return p;
    }

    function fn2(data) {
        console.log(data);
        console.log('第二個(gè)函數(shù)開始執(zhí)行');
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                var num = Math.ceil(Math.random() * 10); // 生成隨機(jī)數(shù)
               console.log(num);
                //num = 0;設(shè)置num=0
                if (num === 0) {
                    console.log('第二個(gè)函數(shù)執(zhí)行完畢');
                    resolve('所有函數(shù)執(zhí)行完畢');
                }
                else{
                    reject("執(zhí)行函數(shù)2失敗");
                }
            }, 2000);
        });
        return p;
    }

    fn1()
        .then(function (data) {
            return fn2(data);
        })
        .then(function (data) {
            console.log(data);
        })
調(diào)用reject()

設(shè)置num =0 調(diào)用resolve()
  • all() 接收一個(gè)函數(shù)數(shù)組,進(jìn)行并發(fā)操作,并將每個(gè)函數(shù)的結(jié)果以數(shù)組的形式返回
function fn1() {
        console.log("第一個(gè)函數(shù)開始執(zhí)行");
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第一個(gè)函數(shù)執(zhí)行完畢');
                resolve('接下來進(jìn)入第二個(gè)函數(shù)');
            }, 1000);
        });
        return p;
    }

    function fn2() {
        console.log('第二個(gè)函數(shù)開始執(zhí)行');
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第二個(gè)函數(shù)執(zhí)行完畢');
                resolve('所有函數(shù)執(zhí)行完畢');
            }, 2000);
        });
        return p;
    }

    Promise.all([fn1(), fn2()])
        .then(function (resut) {
            console.log(resut);
        })
執(zhí)行結(jié)果
  • race()接收函數(shù)數(shù)組,函數(shù)先執(zhí)行完成之后先進(jìn)入下一個(gè)回調(diào)函數(shù)中
    function fn1() {
        console.log("第一個(gè)函數(shù)開始執(zhí)行");
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第一個(gè)函數(shù)執(zhí)行完畢');
                resolve('接下來進(jìn)入第二個(gè)函數(shù)');
            }, 5000);
        });
        return p;
    }

    function fn2() {
        console.log('第二個(gè)函數(shù)開始執(zhí)行');
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第二個(gè)函數(shù)執(zhí)行完畢');
                resolve('所有函數(shù)執(zhí)行完畢');
            }, 1000);
        });
        return p;
    }
    Promise.race([fn1(), fn2()])
        .then(function (resut) {
            console.log(resut);
        })
image.png
  • catch() 當(dāng)then中出現(xiàn)錯(cuò)誤時(shí)不會(huì)中止整個(gè)函數(shù),catch能夠獲取到錯(cuò)誤并進(jìn)行提示
function fn1() {
        console.log("第一個(gè)函數(shù)開始執(zhí)行");
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第一個(gè)函數(shù)執(zhí)行完畢');
                resolve('接下來進(jìn)入第二個(gè)函數(shù)');
            }, 1000);
        });
        return p;
    }

    function fn2() {
        console.log('第二個(gè)函數(shù)開始執(zhí)行');
        var p = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log('第二個(gè)函數(shù)執(zhí)行完畢');
                resolve('所有函數(shù)執(zhí)行完畢');
            }, 1000);
        });
        return p;
    }

     fn1()
         .then(function(data){
             console.log(errPart); //errPart沒有定義
             return fn2(data);
         })
         .then(function (data) {
             console.log(data);
         })
         .catch(function (err) {
             console.log(err);
         })
執(zhí)行結(jié)果

參考鏈接:
https://segmentfault.com/a/1190000009478377
https://www.cnblogs.com/whybxy/p/7645578.html
https://yangbo5207.github.io/wutongluo/ji-chu-jin-jie-xi-lie/shi-san-3001-promise.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Promise 對(duì)象 Promise 的含義 Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函...
    neromous閱讀 8,836評(píng)論 1 56
  • 本文適用的讀者 本文寫給有一定Promise使用經(jīng)驗(yàn)的人,如果你還沒有使用過Promise,這篇文章可能不適合你,...
    HZ充電大喵閱讀 7,457評(píng)論 6 19
  • 目錄:Promise 的含義基本用法Promise.prototype.then()Promise.prototy...
    BluesCurry閱讀 1,566評(píng)論 0 8
  • Promiese 簡單說就是一個(gè)容器,里面保存著某個(gè)未來才會(huì)結(jié)束的事件(通常是一個(gè)異步操作)的結(jié)果,語法上說,Pr...
    雨飛飛雨閱讀 3,491評(píng)論 0 19
  • JavaScript里通常不建議阻塞主程序,尤其是一些代價(jià)比較昂貴的操作,如查找數(shù)據(jù)庫,下載文件等操作,應(yīng)該用異步...
    張歆琳閱讀 2,831評(píng)論 0 12

友情鏈接更多精彩內(nèi)容