提示:记录工作中遇到的需求及解决办法
文章目录
前言
我发现很多人只知道如何常规地使用promise。
在js项目中,promise的使用应该是必不可少的,但我发现在同事和面试官中,很多中级以上的前端仍然坚持promiseInst.then()、promiseInst.catch()、Promise等常规用法等等。即使是 async/await 他们也只知道它但不知道为什么要使用它。
但实际上,Promise 有很多巧妙的高级用法,并且一些高级用法在 alova 请求策略库内部也被广泛使用。
现在,我将与大家分享8个高级使用技巧。希望这些技巧能够对你有所帮助,现在,我们就开始吧。
提示:以下是本篇文章正文内容,下面案例可供参考
1. Promise数组的串行执行
例如,如果你有一组接口需要串行执行,你可能首先想到使用await。
const requestAry = [
() => api.request1(),
() => api.request2(),
() => api.request3()
];
for (const requestItem of requestAry) {
await requestItem();
}
如果使用promise,可以使用then函数串联多个promise,实现串行执行。
const requestAry = [
() => api.request1(),
() => api.request2(),
() => api.request3()
];
const finallyPromise = requestAry.reduce(
(currentPromise, nextRequest) => currentPromise.then(() => nextRequest()),
Promise.resolve() // Create an initial promise for linking promises in the array
);
2. 在新的 Promise 范围之外更改状态
假设你有多个页面,其功能要求在允许使用之前收集用户信息。点击使用某个功能之前,会弹出一个弹框进行信息收集。你会如何实施这个?
以下是不同级别前端同学的实现思路:
初级前端:我写一个模态框,然后复制粘贴到其他页面。效率非常高!
中级前端:这个不好维护。我们需要单独封装这个组件,并在需要的页面引入!
高级前端:安装任何密封的东西!!!把方法调用写在所有页面都可以调用的地方不是更好吗?
想要了解高级前端是如何实现的,以vue3为例,看一下下面的例子。
<!--App.vue -->
<template>
<!-- The following is the modal box component -->
<div class="modal" v-show="visible">
<div> User name: <input v-model="info.name" /> </div>
<!-- Other information -->
<button @click="handleCancel">Cancel</button>
<button @click="handleConfirm">Submit</button>
</div>
<!--Page components-->
</template>
<script setup>
import {
provide} from 'vue';
const visible = ref(false);
const info = reactive({
name: ''});
let resolveFn, rejectFn;
// Pass the information collection function to the following
provide('getInfoByModal', () => {
visible.value = true;
return new