在 uni-app 中切换页面后,怎样中断 onShow 生命周期中的异步函数?-灵析社区

刘一抗二二

![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241001/6768655e47de2e7452d1cf4ac6098419.png) `onShow()` 中有很多的函数调用和异步调用,并且很多很容易出错。当我切换到下一个页面的时候我发现 这个页面 `onShow()` 里面代码仍在执行,有什么好的办法中断吗? 目前能想到的是写一个 `show` 的状态,页面隐藏时改为 `false`,然后每个函数调用前加个判断,感觉有点笨😂。

阅读量:139

点赞量:0

问AI
看下这个案例,可以实现你这个需求。 function executeAsyncFunctions(asyncFunctions) { // 标志变量,用于控制是否停止执行剩余的异步函数 let stopExecution = false; // 异步函数执行器 async function executeAsyncFunction(asyncFunction) { if (!stopExecution) { try { await asyncFunction(); } catch (error) { console.error(error); } } } // 执行异步函数的入口函数 async function execute() { for (const asyncFunction of asyncFunctions) { await executeAsyncFunction(asyncFunction); } } // 停止执行剩余异步函数的函数 function stopExecutionOfRemainingFunctions() { stopExecution = true; } return { execute, stopExecutionOfRemainingFunctions, }; } // 异步函数1 async function asyncFunction1() { console.log('Executing asyncFunction1'); await new Promise((resolve) => setTimeout(resolve, 1000)); console.log('asyncFunction1 completed'); } // 异步函数2 async function asyncFunction2() { console.log('Executing asyncFunction2'); await new Promise((resolve) => setTimeout(resolve, 1000)); console.log('asyncFunction2 completed'); } // 异步函数3 async function asyncFunction3() { console.log('Executing asyncFunction3'); await new Promise((resolve) => setTimeout(resolve, 1000)); console.log('asyncFunction3 completed'); } // 创建异步函数数组 const asyncFunctions = [asyncFunction1, asyncFunction2, asyncFunction3]; // 创建异步函数执行器 const executor = executeAsyncFunctions(asyncFunctions); // 执行异步函数 executor.execute(); // 在某个指定时机停止执行剩余异步函数 setTimeout(() => { executor.stopExecutionOfRemainingFunctions(); console.log('Execution stopped'); }, 2000); 在两秒后停止执行剩余异步函数,执行结果如下: "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241001/fd13195e1ed95c87ed6d8bf7f3f1dc83.png)