momo's Blog.

Promise基本用法

字数统计: 515阅读时长: 2 min
2020/08/15 Share

1. Promise 基本用法

  • 实例化 Promise 对象, 构造函数中传递函数,该函数中用于处理异步任务
  • 通过 resolvereject 两个参数用于处理成功和失败的两种情况,并通过 .then 获取处理结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const p = new Promise(function (resolve, reject){
// 这里用于实现异步任务
setTimeout(function (){
let flag = true
if(flag){
resolve('hello')
}else {
reject('错错了')
}
}, 1000)
})
p.then(function (data){
console.log(data)
},function (info){
console.log(info)
})

2. 基于Promise处理Ajax请求

2.1 处理原生Ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function queryData(url){
const p = new Promise(function (resolve, reject){
// 这里用于实现异步任务
let xhr = new XMLHttpRequest()
xhr.onreadystatechange = function (){
if(xhr.readyState!==4) return 1
if(xhr.readyState===4 && xhr.status === 200){
// 处理正常的情况
resolve(xhr.responseText)
}else {
reject('服务器错误')
}
}
xhr.open('get', url)
xhr.send(null)
})
return p
}
// 调用
queryData('http://localhost:8000/depart/').then(function (data){
console.log(data)
}, function (info){
console.log(info)
})

2.2 then参数中的函数返回值

  1. 返回promise 实例对象
  • 返回的该实例对象可继续调用下一个then方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    queryData('http://localhost:8000/depart/').then(function (data){
    return queryData('http://localhost:8000/depart/')
    })
    .then(function (data){
    return queryData('http://localhost:8000/depart/')
    })
    .then(function (data){
    return queryData('http://localhost:8000/depart/')
    })
    .then(function (data){
    return queryData('http://localhost:8000/depart/')
    })
  1. 返回普通值
  • 返回的普通值会传给下一个then,通过then参数中的函数的参数接收该值
    1
    2
    3
    4
    5
    6
    7
    queryData('http://localhost:8000/depart/').then(function (data){
    return "dwa"
    })
    .then(function (data){
    // 打印出 dwa
    console.log(data)
    })

2.3 Pormise 常用API

  1. 实例方法
  • p.then() 得到异步任务的正确结果
  • p.catch() 获取异常信息
  • p.finally() 成功与否都会执行
  1. 实例方法
  • Promise.all() 并发处理多个异步任务,所有任务全部执行完成后返回结果
  • Promise.race() 并发执行多个任务,其中一个任务执行完成后就能得到结果
    1
    2
    3
    4
    5
    6
    7
    8
    // 传入数组,数组为promise实例对象
    Promise.all([p1,p2,p3]).then(result) => {
    console.log(result)
    }

    Promise.race([p1,p2,p3]).then(result) => {
    console.log(result)
    }
CATALOG
  1. 1. 1. Promise 基本用法
  2. 2. 2. 基于Promise处理Ajax请求
    1. 2.1. 2.1 处理原生Ajax
    2. 2.2. 2.2 then参数中的函数返回值
    3. 2.3. 2.3 Pormise 常用API