Promise異步編程

基本使用方法

一、定義Promise異步執行代碼塊,獲取數據捕獲錯誤

function getJSON(){
    return new Promise((resolve,reject)=>{
        const request = new XMLHttpRequest();
        request.open("GET",url)
        request.onload = function(){
            try{
                if(this.status === 200){
                    resolve(JSON.parse(this.response));
                }else{
                    reject(this.statusText)
                }
            }catch (e){
                reject(e.message)
            }
        }
        request.onerror = function(){
            reject(this.status+":"+this.statusText)
        }
        request.send()
    })
}

複製代碼

二、使用數據獲取錯誤提示

getJSON("data/data.json").then(data => {
    console.log(data)
}).catch( e => console.log(e))
複製代碼

以上對Promise的使用和普通回調函數區別不大,主要應用

一、 優化回調金字塔

getJSON("data/data1.json",function(err,data1){
    getJSON(data1[0].location,function(err,locationInfor){
         getJSON(locationInfor.location,function(err,Infor){
             handle(Infor)
         }
    })
})
複製代碼

鏈式調用Promise

getJSON("data/data1.json")
    .then(data1 => getJSON(data1[0].location))
    .then(locationInfor => getJSON(locationInfor.location)
    .then(Infor => handle(Infor))
    .catch(err => console.log(err))
複製代碼

二、 集中處理多個獨立異步任務

Promise.all([
    getJSON("data/name.json"),
    getJSON("data/age.json"),
    getJSON("data/gender.json")
]).then(results => {
    const name = results[0], age = results[1], gender = results[2];
}).catch(err => console.log(err))
複製代碼

與生成器結合使用

傳入生成器,迭代Promise傳遞結果參數

function async(generator){
    var iterator = generator();
    try{
        handle(iterator.next());
    }catch(e){
        iterator.throw(e)
    }
    fuction handle(iteratorResult){
        if(iteratorResult.done){return;}
        const iteratorValue = iteratorResult.value;
        if(iteratorValue instanceof Promise){
            iteratorValue.then(res => handle(iterator.next(res)))
                .catch(err => iterator.throw(err))
            })
        }
    }
}
複製代碼

傳入生成器

async(function*(){
    try{
        const name = yield getJSON("data/name.json");
        const age = yield getJSON(name[0].location);
    }catch(e){}
})複製代碼
相關文章
相關標籤/搜索