promise

113 阅读1分钟

作用

  • promise封装处理异步操作任务
  • 处理异步操作结果更优雅的方式

三种状态

  • 进行中
  • 成功
  • 失败

使用

//创建promise对象
let promise = new Promise(function (resvoe, reject) {
    //resove 函数 作用:处理成功结果
    // 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);
})

常用方法

  • all同时并发执行,参数是数组,结果也是
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的方法
Promise.all([p1,p2]).then(datas=>{
     console.log(datas)
})
  • race竞争执行,谁先执行完,返回谁
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的方法
Promise.re=ace([p1,p2]).then(data=>{
     console.log(data)
})

async/await

  • 作用:异步操作用同步的写法实现