promise:用同步一样的方式,来书写异步代码。
基本用法
let p = new Promise(function (resolve, reject) { //先声明个promise对象
$.ajax({
url: 'data3.txt',
dataType: 'json',
success(arr) {
resolve(arr)
},
error(err) {
reject(err)
}
})
})
p.then(function (arr) { //promise对象的应用
alert(arr)
}, function (err) {
console.log(err)
})
promise.all
let p1 = new Promise(function (resolve, reject) {
$.ajax({
url: 'data.txt',
dataType: 'json',
success(arr) {
resolve(arr)
},
error(err) {
reject(err)
}
})
})
let p2 = new Promise(function (resolve, reject) {
$.ajax({
url: 'data2.txt',
dataType: 'json',
success(arr) {
resolve(arr)
},
error(err) {
reject(err)
}
})
})
Promise.all([p1,p2]).then(function(result){
alert('全部成功') //返回值resul是个数组
let [arr, json] = result //解构赋值
console.log(arr)
console.log(json)
}, function(err){
console.log(err)
})
优化代码
function creatPromise(url) {
return new Promise(function (resolve, reject) {
$.ajax({
url, //url:url 可以省略一个
dataType: 'json',
success(arr) {
resolve(arr)
},
error(err) {
reject(err)
}
})
})
}
Promise.all([
creatPromise('data.txt'),
creatPromise('data2.txt')
]).then(function (result) {
alert('全部成功') //返回值resul是个数组
let [arr, json] = result //解构赋值
console.log(arr)
console.log(json)
}, function (err) {
console.log(err)
})
高版本jquey本身支持promise
Promise.all([
$.ajax({url:'data.txt', dataType: 'json'}),
$.ajax({url:'data2.txt', dataType: 'json'}),
]).then(result => console.log(result), err => console.log(err))
promise.race 竞速
rece 的用法:同时请求多个资源,哪个请求成功就获取哪一个接口数据
Promise.race([
$.ajax({url:'data.txt', dataType: 'json'}),
$.ajax({url:'data2.txt', dataType: 'json'}),
]).then(result => console.log(result), err => console.log(err))
//只会返回第一个请求通过的接口数据