作用
- promise封装处理异步操作任务
- 处理异步操作结果更优雅的方式
三种状态
使用
let promise = new Promise(function (resvoe, reject) {
setTimeout(function () {
if (true) {
resove('成功执行')
} else {
reject('失败处理')
}
}, 1000)
})
pomise.then(function(result){
})
pomise.catch(function(err){
})
primise封装Ajax请求
function promiseAjax(options) {
return new Promise(function (resolve, reject) {
const xhr = new window.XMLHttpRequest()
let data = forMatData(options.data)
if (options.method.toUpperCase() == 'GET') {
xhr.open(options.method, options.url + '?' + data)
xhr.send()
} else if (options.method.toUpperCase() == 'POST') {
xhr.open(options.method, options.url)
xhr.send(data)
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
let result = JSON.parse(xhr.responseText)
resolve(result)
} else {
reject(xhr.status)
}
}
}
})
}
function forMatData(obj) {
let arr = []
for (const key in obj) {
let str = `${key}=${obj[key]}`
arr.push(str)
}
arr = arr.join('&')
return arr
}
promiseAjax({
method: 'get',
url: 'http://localhost:8088/api/list',
data: {}
}).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})
常用方法
let p1 = promiseAjax({
method: 'get',
url: 'http://localhost:8088/api/list',
data: {}
}).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})
let p2 = promiseAjax({
method: 'get',
url: 'http://localhost:8088/api/list',
data: {}
}).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})
Promise.all([p1,p2]).then(datas=>{
console.log(datas)
})
let p1 = promiseAjax({
method: 'get',
url: 'http://localhost:8088/api/list',
data: {}
}).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})
let p2 = promiseAjax({
method: 'get',
url: 'http://localhost:8088/api/list',
data: {}
}).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})
Promise.re=ace([p1,p2]).then(data=>{
console.log(data)
})
async/await