1. Promise 基本用法
- 实例化
Promise 对象, 构造函数中传递函数,该函数中用于处理异步任务
- 通过
resolve 和 reject 两个参数用于处理成功和失败的两种情况,并通过 .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参数中的函数返回值
- 返回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/') })
|
- 返回普通值
- 返回的普通值会传给下一个then,通过then参数中的函数的参数接收该值
1 2 3 4 5 6 7
| queryData('http://localhost:8000/depart/').then(function (data){ return "dwa" }) .then(function (data){ console.log(data) })
|
2.3 Pormise 常用API
- 实例方法
- p.then() 得到异步任务的正确结果
- p.catch() 获取异常信息
- p.finally() 成功与否都会执行
- 实例方法
- Promise.all() 并发处理多个异步任务,所有任务全部执行完成后返回结果
- Promise.race() 并发执行多个任务,其中一个任务执行完成后就能得到结果
1 2 3 4 5 6 7 8
| Promise.all([p1,p2,p3]).then(result) => { console.log(result) }
Promise.race([p1,p2,p3]).then(result) => { console.log(result) }
|