Promise

promise是一種通過代碼看起來同步并避免回調(diào)地獄而大大簡化異步編程的模式 。promise詳解參照

  1. 一個promise只能 resolvedreject一次,它不能成功或者失敗兩次,也不能從成功轉成失敗,反之亦然。
  2. promise,只要聲明并綁定到變量,就會立即執(zhí)行,為保證promise不是立即執(zhí)行,需要將其封裝到函數(shù)中。
一. 創(chuàng)建promise
var promiseExample = () => {
    new Promise((resolve, reject) => {
        if (Math.random() * 100 < 90) {
            resolve('success,獲取到結果...');
        } else {
            reject(new Error('fail,出現(xiàn)錯誤!'));
        }
    })
}
二. 使用promise
myPromise.then((resolvedValue) => {
    console.log(resolvedValue);
}, (error) => {
    console.log(error);
});

// 適當?shù)腻e誤處理
promiseThatResolves()
    .then(() => {
    throw new Error();
})
    .catch(err => console.log(err));
promise栗子
//分別彈出 Hello World !三個彈窗
function printHello(ready) {
    return new Promise(function (resolve, reject) {
        if (ready) {
            resolve("Hello");
        } else {
            reject("Good bye!");
        }
    });
}
function printWorld() {
    alert("World");
}
function printExclamation() {
    alert("!");
}
printHello(true)
    .then(function (message) {
    alert(message);
})
    .then(printWorld)
    .then(printExclamation);
//一個彈窗 Hello World !
function printHello(ready) {
    return new Promise(function (resolve, reject) {
        if (ready) {
            resolve("Hello");
        } else {
            reject("Good bye!");
        }
    });
}
printHello(true).then(function (message) {
    return message;
}).then(function (message) {
    return message + ' World';
}).then(function (message) {
    return message + '!';
}).then(function (message) {
    alert(message);
});
三. promise 封裝get請求
get: function (url) {   //get請求封裝
    let prodApi = 'http://rmtj.justice.gov.cn/service/rest/mediation.Analysis/collection/';
    var promise = new Promise((resolve, reject) => {
        dd.httpRequest({
            url: prodApi + url,
            method: 'get',
            dataType: 'json',
            success: function (res) {
                if (res.status == 200) {
                    resolve(res);
                } else {
                    reject('請求數(shù)據(jù)失敗');
                }
            },
            error: function (e) {
                reject('網(wǎng)絡出錯');
            }
        })
    });
    return promise;
}
四. promise 封裝異步請求

處理:請求接口2 所需的參數(shù)是請求接口1后的返回值,接口1返回值不及時而報錯的問題 !

// promise封裝接口調(diào)取
getPrintData(baseUrl, url, params) {
    const _that = this;
    return new Promise(function(resolve, reject) {
        _that.restClient.request(baseUrl, url, params).then(
            res => {
                resolve(res);
            },
            error => {
                reject(error);
            }
        )
    })
}
// 上次結果回來后,再次調(diào)用第二個接口
this.getPrintData('nos.UserPrintService', 'retrieve', {}).then(
    checkedItem => {
        // ... 第一次請求結果返回后處理邏輯
        const params = { types: typeParams, volumeId }
        this.getPrintData('npm.Volume_DocumentService', 'print', params).then(res => {
            // ... 第二次請求結果返回后處理邏輯
        });
    },
);
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

  • 大腦昏沉
    凌空一月閱讀 168評論 1 2
  • 很慚愧,到現(xiàn)在為止三毛的作品我只讀了一本——《撒哈拉的故事》,而且還是剛剛結束。 在這本書里,三毛盡情揮灑著自己的...
    傻姑傻閱讀 930評論 12 11
  • 有時候總在想,覺得忙忙活活,時間到哪去了呢?想多一點保障,報了有道考神六級的班,每周一到周五,早上七點晚上九點都要...
    眾知閱讀 184評論 1 0
  • 【天寶鑒藏】20170720學習力踐行D66 踐行:語言啟蒙一二冊,寶寶講。語言啟蒙三四冊,媽媽講。手指謠三首舊一...
    宋duck閱讀 256評論 0 0

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