在ES6標(biāo)準(zhǔn)中出現(xiàn)了 Promise(承諾)
類似于回調(diào)函數(shù)
1:創(chuàng)建Promise的實例
//創(chuàng)建實例
var promise = new Promise(function (resolve, reject) {
if (success) {
//執(zhí)行成功
resolve(data);
}else {
//執(zhí)行失敗
reject(err);
}
})
//調(diào)用then()方法
promise.then(function(value){
//成功時調(diào)用
}, function(value){
//失敗時調(diào)用
})
//或者
promist.then(function(value)){
//成功時調(diào)用
}).cathc(function(value){
//失敗時調(diào)用
})
2:Promise結(jié)合fetch請求的使用
//定義一個方法犬缨,請求數(shù)據(jù)
requestData = (url, postData)=> {
return new Promise(function (resolve, reject) {
//fetch也是一個Promise
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'identity' //編碼方式
},
body: JSON.stringify(postData),
}).then((response) => response.json())
.then((responseData)=> {
resolve(responseData);
})
.catch((err)=> {
console.log('err', err);
reject(err);
});
});
}
}
//調(diào)用上面的方法
this.requestData('http://xxx', {'name': 'jj'})
.then( res=>{
console.log('success');
}).catch( err=>{
//請求失敗
console.log('flied');
3:Promise.all 的用法
Promise.all([promise1, promise2]).then(function(value){
}).catch(function(value){
})
Promise.all中的參數(shù)是一個promise的數(shù)組[promise1, promise2]:數(shù)組中的操作都完成后才會去執(zhí)行后面的響應(yīng)
var req1 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { resolve('First!'); }, 4000);
});
var req2 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { reject('Second!'); }, 3000);
});
Promise.all([req1, req2]).then(function(results) {
console.log('Then: ', one);
}).catch(function(err) {
console.log('Catch: ', err);
});
// From the console:
// Catch: Second!
當(dāng)Promise.all中出現(xiàn)一個promise執(zhí)行失敗reject喳魏,Promise.all會立刻調(diào)用catch
4:Promise.race 的用法
Promise.race([promise1, promise2]).then(function(value){
}).catch(function(value){
})
Promise.race的參數(shù)也是一個promise的數(shù)組[promise1, promise2],不同于Promise.all怀薛,Promise.race的數(shù)組中只需要一個promise執(zhí)行成功刺彩,Promise.race就響應(yīng)接下來的操作
var req1 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { resolve('First!'); }, 8000);
});
var req2 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { resolve('Second!'); }, 3000);
});
Promise.race([req1, req2]).then(function(one) {
console.log('Then: ', one);
}).catch(function(one, two) {
console.log('Catch: ', one);
});
// From the console:
// Then: Second!
這里req2先執(zhí)行完成,則Promise.race的then回調(diào)被執(zhí)行