封裝異步操作
Promise.all([]).then()
/*
Promise-----承諾----消除異步操作(用同步一樣的方式來書寫異步的代碼)
//ajax必須工作在localhost下
異步代碼
resolve 成功了
reject 失敗了
下面用jquery的ajax做練習
當有多個的時候用Promise.all([]).then(function({},function(){})
jquery高版本3.2.1的,本身自帶Promise
$.ajax({
url: 'data/arr.txt',
dataType: 'json'
})
這個ajax有一個返回值,就是Promise對象
let P0 = $.ajax({
url: 'data/arr.txt',
dataType: 'json'
})
console.log(P0)//有Promise對象
Promise的完美寫法與jquery高版本結合
Promise.all([
$.ajax(),
$.ajax()
]).then(results=>{
//對了
},err=>{
//錯了
})
Promise其他的方法
Promise.all([])//全都要成功
Promise.race([])//哪個先讀到先用哪個
*/
/*
let P = new Promise(function(resolve,reject){
$.ajax({
url: 'data/arr.txt',
dataType: 'json',
success(arr){
resolve(arr)
},
error(err){
reject(err);
}
})
})
let P1 = new Promise(function(resolve,reject){
$.ajax({
url: 'data/arr.txt',
dataType: 'json',
success(arr){
resolve(arr)
},
error(err){
reject(err);
}
})
})
P.then(function(arr){//resolve
console.log('成功'+arr)
},function(err){//reject
//console.log('失敗');
console.log(err)
})
*/
//進一步簡化
function createPromise(url){
return new Promise(function(resolve,reject){
$.ajax({
url,//當key和value一樣時,可以省略value
dataType: 'json',
success(arr){
resolve(arr)
},
error(err){
reject(err);
}
})
})
}
/*
Promise.all([
P,P1
]).then(function(arr){
console.log('全都成功了')
console.log(arr)//裝了兩個結果,一個是數組,一個是json
let [res1,res2] = arr;//解構賦值
},function(){
console.log('至少有一個失敗了')
})
*/
Promise.all([
createPromise('data/arr.txt'),
createPromise('data/json.txt')
]).then(function(arr){
//console.log('全都成功了')
//console.log(arr)//裝了兩個結果,一個是數組,一個是json
let [res1,res2] = arr;//解構賦值
},function(){
//console.log('至少有一個失敗了')
})
//高版本jquery自帶Promise對象
let P0 = $.ajax({
url: 'data/arr.txt',
dataType: 'json'
})
console.log(P0)//有Promise對象
//Promise的完美寫法
Promise.all([
$.ajax({url: "data/arr.txt",dataType: 'json'}),
$.ajax({url: 'data/json.txt',dataType: 'json'})
]).then(function(results){
let [arr,json] = results;
console.log(arr,json)
console.log('成功了')
},function(){
console.log('失敗了')
})