1、是什么?
是一种机制,处理未来发生事件的流程。
Promise是异步执行机制,包含:
- 异步操作:在Promise构造函数里,一般是业务请求;
- 回调:
1)通过resolve、reject对外开放了入口;使得回调操作不是内嵌,更像线性代码。
2)通过then,执行异步成功的回调。
回头看 2022-07-06
当初的理解太侧重设计目的,没有认真理解代码形式。导致过段时间再看,只记得是回调|未来,忘了怎么使用。要再注意细节一些。如代码各部分的作用、流程图、增加例子。
用来解决嵌套回调的复杂性,同时增强了设计、明确了过程中的实体。
- executor:执行器,在创建promise实例时直接调用,一般是异步远程后端交互;
- 状态标记和结果传递:定制的函数resolve()、reject();
- 用线性代码的形式实现回调:p.then(resolved(),rejected())。
ps:回到回调的过程,有3个关键动作,在Promise中设计为了更明确实体。
回调动作 | Promise设计的实体 |
---|---|
异步调用 | executor |
异步调用结果判定 | resolve()、reject() |
异步调用的数据 | resolve()、reject() |
回调 | then(),线性呈现 |
Promise生命流程图
2、为什么?
1.“可以一定程度上解决回调地狱”
ps:一般场景下,回调地狱并不难理解,倒是promise的结构和用法给人的困惑更多。
3、如何用?
4、哪些场景?
基本使用
const pp=new Promise((resolve,reject)=>{console.log("1 executor 立即执行")
setTimeout(()=>{console.log("2 executor 中的回调")
resolve(100)
},1000)
console.log("3 executor 立即执行")
})
console.log(pp)
setTimeout(()=>{
console.log(pp)
},1500)
pp.then((data)=>{console.log('pp.then:',data)})
console.log('finish')
执行结果:
用setTimeout模拟异步请求,实现5秒钟打印一次的功能。
//直接写:几乎同时执行
setTimeout(function() {
console.log('m1')
}, 5000)
setTimeout(function() {
console.log('m2')
}, 5000)
setTimeout(function() {
console.log('m3')
}, 5000)
//毁掉嵌套
setTimeout(function() {
console.log(1)
setTimeout(function() {
console.log(2)
setTimeout(function() {
console.log(3)
}, 5000)
}, 5000)
}, 5000)
//promise写法
let p118 = new Promise((resolve, reject) => {
setTimeout(function() {
console.log(1);
resolve()
}, 5 * 1000)
})
p118.then(() => {
//注意:
//1.then的入参一定是个函数;
//2.返回值是自定义的Promise1,控制了与外部的then返回promise状态。
//3.自定义的Promise中再次回调,形成回调的回调。
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log(2);
resolve()
}, 5 * 1000)
})
}).then(() => {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log(3);
resolve()
}, 3 * 1000)
})
5、Promise相关资料
-
Promise面试题整理:
通过考题,掌握重点,包括:
1.Promise的构造函数是同步代码,一创建就执行;
2.then()是回调函数。注意:仅当then的入参是函数时,如果是普通代码,则直接执行(变量洞穿?);
3.promise的状态只能改一次;
4.then、catch可以被多次调用。对比状态只能改一次。
https://segmentfault.com/a/1190000021844647?utm_source=sf-related -
Promise入门详解和基本用法:https://www.cnblogs.com/qianguyihao/p/12660393.html
-
Promise的进阶:async\await
https://blog.csdn.net/major_zhang/article/details/79154287