文章目录
- Promise 教程
- 为什么要使用 Promise
- Promise 的作用
- 面试题
- 输出顺序(二星)
- 输出顺序(三星)
- 快手面试题
- 深信服面试题
- **链式调用原则**
- Promise 链式调用原则
- 返回值传递
- 错误冒泡
- 链的拆分与合并
- 隐式 Promise 解析
- 链的终止
Promise 教程
Promise 是 JavaScript 中用于处理异步操作的对象,代表一个异步操作的最终完成或失败及其结果值。它有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。
为什么要使用 Promise
Promise 的作用
Promise 是一种用于处理异步操作的编程模式,能够更优雅地管理异步代码,避免回调地狱(Callback Hell),提高代码的可读性和可维护性。
Promise 实现
// 许下一个承诺,有三种状态// promise状态---> 等待 ---> 成功或者失败// reslove = 成功的回调函数// reject = 失败的回调函数letisForget=true;// true => 得到礼物// false => 道歉letcn=newPromise((reslove,reject)=>{if(isForget){letl={color:'green'price:'$99'}reslove(l)}else{leterr=newError('道歉')reject(err)}})lettest=function(){cn.then((res)=>{console.log(res)}).catch((err)=>{console.log(err.message)})}test()为什么Promise能代替回调函数,比回调函数做的更好
- 回调函数嵌套是
N层的,Promise永远只有两层,代码更加清晰简洁
<script>// 常规回调函数run(0);setTimeout(()=>{run(1);setTimeout(()=>{run(2);setTimeout(()=>{run(3);},1000);},1000);},1000);// 使用 setTimeout 给每个 run 调用添加定时器setTimeout(()=>run(0),0);newPromise((resolve)=>{setTimeout(()=>{run(1);resolve();},100);}).then(()=>{setTimeout(()=>{run(2);},200);}).then(()=>{setTimeout(()=>{run(3);},300);});</script>面试题
输出顺序(二星)
<script>// Promise 的构造函数 同步执行// new Promise 是一个宏任务constpromise=newPromise((resolve,reject)=>{console.log(1);resolve();console.log(2);})// .then .catch 是有微任务 => 异步执行promise.then(()=>{console.log(3);})// 同步console.log(4);// 1 2 4 3</script>输出顺序(三星)
<script>// 构造函数只执行一次,.then可以多次调用constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{//只执行一次console.log(1);//返回值resolve('2');},1000)})//返回 2promise.then((res)=>{console.log(res);})//返回 2promise.then((res)=>{console.log(res);})</script>快手面试题
填写括号内的内容,两秒后返回一个值
<script>functionsleep(time){【returnnewPromise(()=>{setTimeout(()=>{console.log('timeout')},time)】})}sleep(2000).then(()=>{console.log('1');})</script>深信服面试题
走了.then,但返回一个Error
<script>// 链式调用// 有两个.then => 代表有两个promise//链式调用的原则 上一个promise返回的结果,不管是成功还是失败,都会把你当成第二个promise成功时的回调Promise.resolve().then(()=>{returnnewError('error!!!')}).then((res)=>{console.log('res:',res)}).catch((err)=>{console.log('err:',err)})</script>补充知识点
链式调用原则
Promise 链式调用原则
Promise 的链式调用是异步编程的核心特性之一,通过.then()和.catch()方法实现顺序执行异步操作。以下是链式调用的关键原则:
返回值传递
每次调用.then()或.catch()会返回一个新的 Promise,后续链式调用基于前一个 Promise 的返回值。如果回调函数返回非 Promise 值,该值会作为下一个.then()的输入;如果返回 Promise,则等待其解决后再传递结果。
fetchData().then(data=>process(data))// 返回处理后的数据.then(result=>save(result));// result 是 process(data) 的返回值错误冒泡
链式调用中,错误会一直向后传递,直到被.catch()捕获。中间的任何.then()跳过,直接跳转到最近的错误处理函数。
fetchData().then(data=>mightThrowError(data)).then(result=>console.log(result)).catch(error=>console.error(error));// 捕获前面所有步骤的错误链的拆分与合并
通过返回新的 Promise,可以拆分或合并逻辑链。例如,并行执行多个异步操作时,可用Promise.all合并结果。
fetchUser().then(user=>Promise.all([fetchProfile(user.id),fetchPosts(user.id)])).then(([profile,posts])=>mergeData(profile,posts));隐式 Promise 解析
如果.then()的回调未显式返回 Promise,引擎会自动将返回值包装为 resolved Promise。若抛出异常,则包装为 rejected Promise。
fetchData().then(data=>{if(!data)thrownewError('No data');// 自动转为 rejected Promisereturndata.value;// 自动转为 resolved Promise});链的终止
未处理的 rejected Promise 可能导致静默失败。建议始终在链式调用末尾添加.catch(),或使用async/await的try-catch结构。
fetchData().then(handleData).catch(logError);// 终止链并处理所有可能的错误通过遵循这些原则,可以构建清晰、可维护的异步代码流程。