promise是一種通過代碼看起來同步并避免回調(diào)地獄而大大簡化異步編程的模式 。promise詳解參照
- 一個
promise只能resolved或reject一次,它不能成功或者失敗兩次,也不能從成功轉成失敗,反之亦然。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 => {
// ... 第二次請求結果返回后處理邏輯
});
},
);