Promise
参考视频:尚硅谷Web前端Promise教程从入门到精通
回调地狱问题
1、什么是回调地狱?
回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调执行的条件

2、回调地狱的缺点?
不便于阅读,不便于异常处理
3、解决方案?
promise 链式调用
4、终极解决方案?
async/await
Promise是什么
Promise 是 JS 中进行异步编程的新解决方案
**本质**:Promise 是一个构造函数
**作用**:promise 对象用来封装一个**异步操作**并可以获取其成功/失败的结果值
为什么要用 Promise?
指定回调函数的方式更加灵活
1.旧的: 必须在启动异步任务前指定
2.promise: 启动异步任务 => 返回promie对象 => 给promise对象绑定回调函数(甚至可以在异步任务结束后指定/多个)
Promise 的状态改变
三种状态 pending(初始状态) resolved rejected
一个 promise 对象只能改变一次,无论变为成功还是失败, 都会有一个结果数据成功的结果数据一般称为 value, 失败的结果数据一般称为 reason
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
| const p = new Promise((resolve, reject) => {
setTimeout(() => { const time = Date.now() if (time%2===1) { resolve('成功的值 '+ time) } else { reject('失败的值' + time) } }, 2000) })
p.then(value => { console.log('成功的 value: ', value) },reason => { console.log('失败的 reason: ', reason) })
|
Promise API
1、Promise 构造函数: Promise (excutor) {}
(1) executor 函数: 执行器 (resolve, reject) => {}
(2) resolve 函数: 内部定义成功时我们调用的函数 value => {}
(3) reject 函数: 内部定义失败时我们调用的函数 reason => {}
说明: executor 会在 Promise 内部立即同步调用,异步操作在执行器中执行
2、Promise.prototype.then 方法: (onResolved, onRejected) => {}
(1) onResolved 函数: 成功的回调函数 (value) => {}
(2) onRejected 函数: 失败的回调函数 (reason) => {}
说明: 指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调返回一个新的 promise 对象
3、Promise.prototype.catch 方法: (onRejected) => {}
(1) onRejected 函数: 失败的回调函数 (reason) => {}
说明: then()的语法糖, 相当于: then(undefined, onRejected)
4、Promise.resolve 方法: (value) => {}
(1) value: 成功的数据或 promise 对象
说明: 返回一个成功/失败的 promise 对象
5、Promise.reject 方法: (reason) => {}
(1) reason: 失败的原因
说明: 返回一个失败的 promise 对象
6、Promise.all 方法: (promises) => {}
(1) promises: 包含 n 个 promise 的数组
说明: 返回一个新的 promise, 只有所有的 promise 都成功才成功, 只要有一个失败了就直接失败
7、Promise.race 方法: (promises) => {}
(1) promises: 包含 n 个 promise 的数组
说明: 返回一个新的 promise, 第一个完成的 promise 的结果状态就是最终的结果状态
关键问题
一、如何改变 promise 的状态?
(1) resolve(value): 如果当前是 pending 就会变为 resolved
(2) reject(reason): 如果当前是 pending 就会变为 rejected
(3) 抛出异常: 如果当前是 pending 就会变为 rejected
1 2 3 4 5 6 7 8
| let p = new Promise((resolve, reject) => { });
|
二、一个 promise 指定多个成功/失败回调函数, 都会调用吗?
当 promise 改变为对应状态时都会调用
1 2 3 4 5 6 7 8 9 10 11
| let p = new Promise((resolve, reject) => { });
p.then(value => { console.log(value); });
p.then(value => { alert(value); });
|
三、⭐️⭐️改变 Promise 状态和指定回调函数谁先谁后?⭐️⭐️(对应P20)
(1) 都有可能, 正常情况下是先**指定**回调再改变状态, 但也可以先改状态再指定回调
(2) 如何先改状态再指定回调?
① 在执行器中直接调用 resolve()/reject()
② 延迟更长时间才调用 then()
(3) 什么时候才能得到数据?
① 如果先指定的回调, 那当状态发生改变时, 回调函数就会调用, 得到数据
② 如果先改变的状态, 那当指定回调时, 回调函数就会调用, 得到数据
四、promise.then()返回的新 Promise对象 的结果状态由什么决定?
(1) 简单表达: 由 then()指定的回调函数执行的结果决定
(2) 详细表达:
① 如果抛出异常, 新 promise 变为 rejected, reason 为抛出的异常
② 如果返回的是非 promise 的任意值, 新 promise 变为 resolved, value 为返回的值
③ 如果返回的是另一个新 promise, 此 promise 的结果就会成为新 promise 的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| let p = new Promise((resolve, reject) => { resolve('ok'); });
let result = p.then(value => { console.log(value); }, reason => { console.warn(reason); }); console.log(result);
|
五、⭐️⭐️Promise关键问题 - 如何串联多个任务⭐️⭐️
(1) promise 的 then()返回一个新的 promise, 可以开成 then()的链式调用
(2) 通过 then 的链式调用串连多个同步/异步任务
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
| let p = new Promise((resolve, reject) => { console.log(1) setTimeout(() => { resolve('OK'); }, 2000); }); p.then(value => { return new Promise((resolve, reject) => { console.log(2) setTimeout(() => { console.log(value); resolve("successA"); },2000) }); }).then(value => { return new Promise((resolve, reject) => { console.log(3) setTimeout(() => { console.log(value); resolve("successB"); },2000) }); }).then(value => { console.log(value); })
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| let status = "" setTimeout(()=>{ console.log(1) status = "OK" setTimeout(()=>{ console.log(2) console.log(status) status = "successA" setTimeout(()=>{ console.log(3) console.log(status) status = "successB" setTimeout(()=>{ console.log(status) },0) },2000) },2000) },2000)
|
说明:两段代码实现功能一样,可以看到使用promise后产生的明显的区别
六、 Promise 异常传透?
(1) 当使用 promise 的 then 链式调用时, 可以在最后指定失败的回调,
(2) 前面任何操作出了异常, 都会传到最后失败的回调中处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| let p = new Promise((resolve, reject) => { setTimeout(() => { resolve('OK'); }, 1000); });
p.then(value => { throw '失败啦!'; }).then(value => { console.log(222); }).then(value => { console.log(333); }).catch(reason => { console.warn(reason); });
|
七、中断 Promise 链?
(1) 当使用 promise 的 then 链式调用时, 在中间中断, 不再调用后面的回调函数
(2) 办法: 在回调函数中返回一个 pendding 状态的 promise 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| let p = new Promise((resolve, reject) => { setTimeout(() => { resolve('OK'); }, 1000); });
p.then(value => { console.log(111); return new Promise(() => {}); }).then(value => { console.log(222); }).then(value => { console.log(333); }).catch(reason => { console.warn(reason); });
|
自定义(手写)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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
| function Promise(executor){ this.PromiseState = 'pending'; this.PromiseResult = null; this.callbacks = []; const self = this; function resolve(data){ if(self.PromiseState !== 'pending') return; self.PromiseState = 'fulfilled'; self.PromiseResult = data; setTimeout(() => { self.callbacks.forEach(item => { item.onResolved(data); }); }); } function reject(data){ if(self.PromiseState !== 'pending') return; self.PromiseState = 'rejected'; self.PromiseResult = data; setTimeout(() => { self.callbacks.forEach(item => { item.onRejected(data); }); }); } try{ executor(resolve, reject); }catch(e){ reject(e); } }
Promise.prototype.then = function(onResolved, onRejected){ const self = this; if(typeof onRejected !== 'function'){ onRejected = reason => { throw reason; } } if(typeof onResolved !== 'function'){ onResolved = value => value; } return new Promise((resolve, reject) => { function callback(type){ try{ let result = type(self.PromiseResult); if(result instanceof Promise){ result.then(v => { resolve(v); }, r=>{ reject(r); }) }else{ resolve(result); } }catch(e){ reject(e); } } if(this.PromiseState === 'fulfilled'){ setTimeout(() => { callback(onResolved); }); } if(this.PromiseState === 'rejected'){ setTimeout(() => { callback(onRejected); }); } if(this.PromiseState === 'pending'){ this.callbacks.push({ onResolved: function(){ callback(onResolved); }, onRejected: function(){ callback(onRejected); } }); } }) }
Promise.prototype.catch = function(onRejected){ return this.then(undefined, onRejected); }
Promise.resolve = function(value){ return new Promise((resolve, reject) => { if(value instanceof Promise){ value.then(v=>{ resolve(v); }, r=>{ reject(r); }) }else{ resolve(value); } }); }
Promise.reject = function(reason){ return new Promise((resolve, reject)=>{ reject(reason); }); }
Promise.all = function(promises){ return new Promise((resolve, reject) => { let count = 0; let arr = []; for(let i=0;i<promises.length;i++){ promises[i].then(v => { count++; arr[i] = v; if(count === promises.length){ resolve(arr); } }, r => { reject(r); }); } }); }
Promise.race = function(promises){ return new Promise((resolve, reject) => { for(let i=0;i<promises.length;i++){ promises[i].then(v => { resolve(v); },r=>{ reject(r); }) } }); }
|
CLASS版本
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
| class Promise{ constructor(executor){ this.PromiseState = 'pending'; this.PromiseResult = null; this.callbacks = []; const self = this; function resolve(data){ if(self.PromiseState !== 'pending') return; self.PromiseState = 'fulfilled'; self.PromiseResult = data; setTimeout(() => { self.callbacks.forEach(item => { item.onResolved(data); }); }); } function reject(data){ if(self.PromiseState !== 'pending') return; self.PromiseState = 'rejected'; self.PromiseResult = data; setTimeout(() => { self.callbacks.forEach(item => { item.onRejected(data); }); }); } try{ executor(resolve, reject); }catch(e){ reject(e); } }
then(onResolved,onRejected){ const self = this; if(typeof onRejected !== 'function'){ onRejected = reason => { throw reason; } } if(typeof onResolved !== 'function'){ onResolved = value => value; } return new Promise((resolve, reject) => { function callback(type){ try{ let result = type(self.PromiseResult); if(result instanceof Promise){ result.then(v => { resolve(v); }, r=>{ reject(r); }) }else{ resolve(result); } }catch(e){ reject(e); } } if(this.PromiseState === 'fulfilled'){ setTimeout(() => { callback(onResolved); }); } if(this.PromiseState === 'rejected'){ setTimeout(() => { callback(onRejected); }); } if(this.PromiseState === 'pending'){ this.callbacks.push({ onResolved: function(){ callback(onResolved); }, onRejected: function(){ callback(onRejected); } }); } }) }
catch(onRejected){ return this.then(undefined, onRejected); }
static resolve(value){ return new Promise((resolve, reject) => { if(value instanceof Promise){ value.then(v=>{ resolve(v); }, r=>{ reject(r); }) }else{ resolve(value); } }); }
static reject(reason){ return new Promise((resolve, reject)=>{ reject(reason); }); }
static all(promises){ return new Promise((resolve, reject) => { let count = 0; let arr = []; for(let i=0;i<promises.length;i++){ promises[i].then(v => { count++; arr[i] = v; if(count === promises.length){ resolve(arr); } }, r => { reject(r); }); } }); }
static race (promises){ return new Promise((resolve, reject) => { for(let i=0;i<promises.length;i++){ promises[i].then(v => { resolve(v); },r=>{ reject(r); }) } }); } }
|
async 与 await
async 函数
1、函数的返回值为 promise 对象
2、promise 对象的结果由 async 函数执行的返回值决定
1 2 3 4 5 6 7 8 9 10 11
| async function main(){ throw "Oh NO"; }
|
await 表达式
1、await 右侧的表达式一般为 promise 对象, 但也可以是其它的值
2、如果表达式是 promise 对象, await 返回的是 promise 成功的值
3、如果表达式是其它值, 直接将此值作为 await 的返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| async function main(){ let p = new Promise((resolve, reject) => { reject('Error'); }) try{ let res3 = await p; }catch(e){ console.log(e); } } main();
|
注意
1、await 必须写在 async 函数中, 但 async 函数中可以没有 await
2、如果 await 的 promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理
async与await结合
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
|
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();
|
说明:当你想实现读取项目目录下三个html文件并将文件的内容拼接(三个文件的内容按顺序拼接)由于fs.readFile是一个异步的方法,必须通过回调函数的形式进行执行才能得到想要的文件,产生了回调地狱.此时场景使用async,await会更加方便简单明了,解决回调地狱问题