异步编程是什么
异步编程
- fs 文件操作
1
| require('fs').readFile('./index.html', (err,data)=>{})
|
- 数据库操作
- AJAX
1
| $.get('/server', (data)=>{})
|
- 定时器
1
| setTimeout(()=>{}, 2000);
|
为什么要用 Promise
1.2.1. 指定回调函数的方式更加灵活
旧的: 必须在启动异步任务前指定
promise: 启动异步任务 => 返回promie对象 => 给promise对象绑定回调函数(甚至可以在异步任务结束后指定/多个)
1.2.2. 支持链式调用, 可以解决回调地狱问题
什么是回调地狱? 回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调执行的条件
回调地狱的缺点?
使用
1.promise实现对定时器的封装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>基本使用</title> <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h2 class="page-header">Promise 初体验</h2> <button class="btn btn-primary" id="btn">点击抽奖</button> </div> <script> function rand(m,n){ return Math.ceil(Math.random() * (n-m+1)) + m-1; }
const btn = document.querySelector('#btn'); btn.addEventListener('click', function(){
const p = new Promise((resolve, reject) => { setTimeout(() => { let n = rand(1, 100); if(n <= 30){ resolve(n); }else{ reject(n); } }, 1000); });
console.log(p); p.then((value) => { alert('恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券, 您的中奖数字为 ' + value); }, (reason) => { alert('再接再厉, 您的号码为 ' + reason); });
}); </script> </body>
</html>
|
2.实现对读取文件函数的封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
function mineReadFile(path){ return new Promise((resolve, reject) => { require('fs').readFile(path, (err, data) =>{ if(err) reject(err); resolve(data); }); }); }
mineReadFile('./resource/content.txt') .then(value=>{ console.log(value.toString()); }, reason=>{ console.log(reason); });
|
3-util.promisify方法
1 2 3 4 5 6 7 8 9 10 11 12 13
|
const util = require('util');
const fs = require('fs');
let mineReadFile = util.promisify(fs.readFile);
mineReadFile('./resource/content.txt').then(value=>{ console.log(value.toString()); });
|
4.封装getAjax操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Promise封装AJAX操作</title> </head> <body> <script>
function sendAJAX(url){ return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("GET", url); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status < 300){ resolve(xhr.response); }else{ reject(xhr.status); } } } }); } sendAJAX('https://api.apiopen.top/getJok') .then(value => { console.log(value); }, reason => { console.warn(reason); }); </script> </body> </html>
|
Promise的理解
是什么
Promise 的状态
实例对象中的一个属性 『PromiseState
』
- pending 未决定的
- resolved / fullfilled 成功
- rejected 失败
pending 变为 resolved
pending 变为 rejected
说明: 只有这 2 种, 且一个 promise 对象只能改变一次, 无论变为成功还是失败, 都会有一个结果数据,成功的结果数据一般称为 value, 失败的结果数据一般称为 reason
Promise 对象的值
实例对象中的另一个属性 『PromiseResult』
保存着异步任务『成功/失败』的结果
基本流程

相关API
Promise 构造函数: Promise (excutor) {}
(1) executor 函数: 执行器 (resolve, reject) => {}
(2) resolve 函数: 内部定义成功时我们调用的函数 value => {}
(3) reject 函数: 内部定义失败时我们调用的函数 reason => {}
说明: executor 会在 Promise 内部立即同步调用,异步操作在执行器中执行
Promise.prototype.then
方法: (onResolved, onRejected) => {}
(1) onResolved 函数: 成功的回调函数 (value) => {}
(2) onRejected 函数: 失败的回调函数 (reason) => {}
说明: 指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调返回一个新的 promise 对象
Promise.prototype.catch
方法: (onRejected) => {}
(1) onRejected 函数: 失败的回调函数 (reason) => {}
说明: then()的语法糖, 相当于: then(undefined, onRejected)
Promise.resolve
方法: (value) => {}
(1) value: 成功的数据或 promise 对象
说明: 返回一个成功/失败的 promise 对象
Promise.reject
方法: (reason) => {}
(1) reason: 失败的原因
说明: 返回一个失败的 promise 对象
Promise.all
方法: (promises) => {}
(1) promises: 包含 n 个 promise 的数组
说明: 返回一个新的 promise, 只有所有的 promise 都成功才成功, 只要有一个失败了就直接失败
Promise.race
方法: (promises) => {}
(1) promises: 包含 n 个 promise 的数组
说明: 返回一个新的 promise, 第一个完成的 promise 的结果状态就是最终的结果状态
几个关键问题
如何改变 promise 的状态?
resolve(value)
: 如果当前是 pending 就会变为 resolved
reject(reason)
: 如果当前是 pending 就会变为 rejected
- 抛出异常: 如果当前是 pending 就会变为 rejected
一个 promise 指定多个成功/失败回调函数, 都会调用吗?
改变 promise 状态和指定回调函数谁先谁后?
- 都有可能, 正常情况下是先指定回调再改变状态, 但也可以先改状态再指定回调
- 如何先改状态再指定回调?
- 在执行器中直接调用 resolve()/reject()
- 延迟更长时间才调用 then()
- 什么时候才能得到数据?
- 如果先指定的回调, 那当状态发生改变时, 回调函数就会调用, 得到数据
- 如果先改变的状态, 那当指定回调时, 回调函数就会调用, 得到数据
promise.then()返回的新 promise 的结果状态由什么决定?
- 简单表达: 由 then()指定的回调函数执行的结果决定
- 详细表达:
- 如果抛出异常, 新 promise 变为 rejected, reason 为抛出的异常
- 如果返回的是非 promise 的任意值, 新 promise 变为 resolved, value 为返回的值
- 如果返回的是另一个新 promise, 此 promise 的结果就会成为新 promise 的结果
promise 如何串连多个操作任务?
- promise 的 then()返回一个新的 promise, 可以开成 then()的链式调用
- 通过 then 的链式调用串连多个同步/异步任务
promise 异常传透?
- 当使用 promise 的 then 链式调用时, 可以在最后指定失败的回调,
- 前面任何操作出了异常, 都会传到最后失败的回调中处理
中断 promise 链?
- 当使用 promise 的 then 链式调用时, 在中间中断, 不再调用后面的回调函数
- 办法: 在回调函数中返回一个 pendding 状态的 promise 对象
自定义(手写)Promise
定义整体结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
(function (window) {
function Promise(excutor) { }
Promise.prototype.then = function (onResolved, onRejected) { }
Promise.prototype.catch = function (onRejected) { }
Promise.resolve = function (value) { }
Promise.reject = function (reason) { }
Promise.all = function (promises) { }
Promise.race = function (promises) { }
window.Promise = Promise })(window)
|
Promise 构造函数的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
function Promise(excutor) { const self = this self.status = 'pending' self.data = undefined self.callbacks = []
function resolve(value) { if(self.status!=='pending') { return } self.status = 'resolved' self.data = value if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(obj => { obj.onResolved(value) }) }) } }
function reject(reason) { if(self.status!=='pending') { return } self.status = 'rejected' self.data = reason setTimeout(() => { self.callbacks.forEach(obj => { obj.onRejected(reason) }) }) } try { excutor(resolve, reject) } catch (error) { reject(error) } }
|
promise.then()/catch()的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
Promise.prototype.then = function (onResolved, onRejected) { const self = this onResolved = typeof onResolved==='function' ? onResolved : value => value onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason} return new Promise((resolve, reject) => {
function handle(callback) { try { const x = callback(self.data) if (x instanceof Promise) { x.then(resolve, reject) } else { resolve(x) } } catch (error) { reject(error) } } if (self.status === 'resolved') { setTimeout(() => { handle(onResolved) }) } else if (self.status === 'rejected') { setTimeout(() => { handle(onRejected) }) } else { self.callbacks.push({ onResolved(value) { handle(onResolved) }, onRejected(reason) { handle(onRejected) } }) } }) }
Promise.prototype.catch = function (onRejected) { return this.then(null, onRejected) }
|
2.4. Promise.resolve()/reject()的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
Promise.resolve = function (value) { return new Promise((resolve, reject) => { if (value instanceof Promise) { value.then(resolve, reject) } else { resolve(value) } }) }
Promise.reject = function (reason) { return new Promise((resolve, reject) => { reject(reason) }) }
|
2.5. Promise.all/race()的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
Promise.all = function (promises) { return new Promise((resolve, reject) => { let resolvedCount = 0 const promisesLength = promises.length const values = new Array(promisesLength) for (let i = 0; i < promisesLength; i++) { Promise.resolve(promises[i]).then( value => { values[i] = value resolvedCount++ if(resolvedCount===promisesLength) { resolve(values) } }, reason => { reject(reason) } ) } }) }
Promise.race = function (promises) { return new Promise((resolve, reject) => { for (var i = 0; i < promises.length; i++) { Promise.resolve(promises[i]).then( (value) => { resolve(value) }, (reason) => { reject(reason) }) } }) }
|
2.6. Promise.resolveDelay()/rejectDelay()的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
Promise.resolveDelay = function (value, time) { return new Promise((resolve, reject) => { setTimeout(() => { if (value instanceof Promise) { value.then(resolve, reject) resolve(val), 如果 value 失败了, 调用 reject(reason) } else { resolve(value) } }, time); }) }
Promise.rejectDelay = function (reason, time) { return new Promise((resolve, reject) => { setTimeout(() => { reject(reason) }, time) }) }
|
四、async 与 await
3.1. async 函数
函数的返回值为 promise 对象
promise 对象的结果由 async 函数执行的返回值决定
3.2. await 表达式
await 右侧的表达式一般为 promise 对象, 但也可以是其它的值
如果表达式是 promise 对象, await 返回的是 promise 成功的值
如果表达式是其它值, 直接将此值作为 await 的返回值
3.3注意
await 必须写在 async 函数中, 但 async 函数中可以没有 await
如果 await 的 promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| const fs = require('fs'); const util = require('util'); const mineReadFile = util.promisify(fs.readFile);
async function main(){ try{ let data1 = await mineReadFile('./resource/1x.html'); let data2 = await mineReadFile('./resource/2.html'); let data3 = await mineReadFile('./resource/3.html'); console.log(data1 + data2 + data3); }catch(e){ console.log(e.code); } }
main();
|