带有异步函数的闭包

前端开发 2026-07-09

所以我发现闭包(也就是返回整个函数的函数)是一个挺不错的办法,可以让一个函数保留变量而不至于过多污染全局变量。现在的问题是,当我把这种做法应用到异步函数时,返回的只是一个Promise,而不是实际的函数。

我想要实现的伪代码是

async function outer()
    //keep these alive for inner
    var step1,step2
    async function inner() {
        //if step1 was already okay, skip
        if(step1!="ok") {
            await(fetch(...).then(result => {
                step1="ok";
            })
            .catch(e => {
                step1="error";
                return;
            });
        }
        //if we failed, nope out of here and retry
        if(step1 != "ok") return;
        //if step2 was already okay, skip
        if(step2!="ok") {
            await(something(...).then(result => {
                step2="ok";
            }
            })
            .catch(e => {
                step2="error";
                return;
            });
        }
        //if step2 wasnt successful, nope out of here
        if(step2!="ok") return;
        //the main part, can also fail, causing another possible need for a rerun.
        dostuff();
    }
    return inner;
}
const closure=outer();

基本上我想让inner能被重复执行,例如把它作为按钮事件监听器的一部分来使用,保留它自己的状态,并跳过已经完成的部分。

全局变量确实是一个简单的解决办法,但人们总说全局变量不好,因此希望能少用一些全局变量。

解决方案

outer 改为普通函数;它不使用任何 async 的特性。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章