起因
大家都知道做前端開發(fā)的時候最讓人頭痛的就是處理異步請求的情況陶因,在請求到的成功回調函數(shù)里繼續(xù)寫函數(shù),長此以往形成了回調地獄垂蜗。
function load() {
$.ajax({
url: 'xxx.com',
data: 'jsonp',
success: function(res) {
init(res, function(res) {
render(res, function(res) {
// 一層一層又一層
});
});
}
}
}
load();
這樣的代碼看層級少了當然還是可以湊合看的楷扬,但是多起來的話,那就難以維護了贴见,無論是開發(fā)者自身還是同事來接手項目烘苹,都是極其無奈的!還要我怎樣片部,要怎樣镣衡,怎樣,樣档悠。
于是乎 出現(xiàn)了Promise
當年在聽到關于Promise的報道的時候沒有太多關注廊鸥,只是知道是解決回調地獄問題的,一種異步請求解決方案而已辖所。
后來在工作當中發(fā)現(xiàn)JQ也實現(xiàn)了相關的方法惰说,上代碼
$.get('xxx.php').done(function() {
alert('成功的回調'); // 相當于Promise的resolve()
});
現(xiàn)在看來,真的和Promise差不多呢缘回。那么我們回到今天的主角來
先介紹一下Promise的三種狀態(tài):
- Pending 創(chuàng)建Promise對象時的初始狀態(tài)
- Fulfilled 成功時的狀態(tài)
- Rejected 失敗時的狀態(tài)
說完了狀態(tài)直接上代碼吆视,我們得會用才行:
還以上面load函數(shù)的例子
// then方法是用的最多的了
// 按照then來執(zhí)行成功和失敗的回調函數(shù)
function load() {
return new Promise((resovel, reject) => {
$.ajax({
url: 'xxx.com',
data: 'jsonp',
success: function(res) {
resolve(res);
},
error: function(err) {
reject(err);
}
});
});
}
// 用一下
load().then(data => {
console.log(data); // 請求到的數(shù)據(jù)
console.log('請求數(shù)據(jù)成功');
}, err => {
console.log('請求失敗');
});
除了處理請求,Promise還可以寫在普通的函數(shù)中
function init(options) {
return new Promise((resolve, reject) => {
if (options.id) {
console.log('你是唯一')
resolve(options.id);
} else {
console.log('不行酥宴,不行');
reject()
}
});
}
init({id: 110})
.then(id => {
console.log(id); // 110
let obj = {id, nickname: '左夕'};
return obj;
})
.then(other => {
console.log(other); // { id: 110, nickname: '左夕' }
});
Promise.all和Promise.race有點類型
all是Promise的狀態(tài)都為成功才表示成功
race是Promise的狀態(tài)是有一個先成功的狀態(tài)了啦吧,就表示成功
最近很火的axios其實就是調用了Promise,寫法也是很相似的
由于它是第三方包幅虑,需要npm i axios安裝一下
// 發(fā)個get請求
axios.get('user/', {
id,
username
}).then(res => {
console.log(res); // 成功
}).catch(err => {
console.log(err); // 失敗
});
// 再來個post請求
axios.post('login/', {
username,
password
}).then(res => {
console.log(res); // 成功
}).catch(err => {
console.log(err); // 失敗
});
// 也有all的操作
function getUser() {
return axios.get('/user');
}
function sendMsg() {
return axios.post('/info', {msg});
}
axios.all([getUser(), sendMsg()]).then(res => {})
總結一下:Promise常用的就是這些了丰滑,then返回的也是一個Promise對象,所以可以繼續(xù)調用.then方法。有說的不對的地方褒墨,還望指出炫刷。