避免在匿名异步函数中变得不确定

发布于 2025-02-10 00:02:57 字数 1110 浏览 1 评论 0原文

我遇到了一个问题,因为jQuery在for循环中变得不确定。我找到了一个解决方案,但是我试图理解问题的原因。当然,我愿意反馈我的编程风格和选择。无论如何,我离题...

背景

在浏览器中完成的资产管理系统中,在书签上工作,以自动化一项繁琐的任务。我想这样做有一百万个更好的方法,但是由于技术和政治约束,不能。

自动化的任务很长,必须重复多次,因此必须是无障碍物,因此可以使用进度栏更新DOM。

问题

以下代码可用于单个迭代。但是,在连续的迭代中,由于UI_Progressbar中需要jQuery,因此jQuery变得不确定,这会导致代码崩溃。

ui_render完成后,$变为未定义,但是我不知道为什么可能是这种情况。

async function UI_Render()
{
    return new Promise(resolve => setTimeout(resolve, 10)); 
}

//i = [0,100] is for the example.
for(let i = 0; i <= 100; i++)
{
    await DoStuff(i);
    await UI_ProgressBar(i).then(async function () {
        await UI_Render();
    });
}

临时解决方案

当前我的临时解决方案是使用临时变量容纳jQuery,但这不是理想的。

async function UI_Render(){
    let v = $;
    var p = new Promise(resolve => setTimeout(resolve, 10)); 
    $ = v;
    return p; 
}

如果要测试代码,这里是可以粘贴到开发人员控制台的原始提取物: https:// pastebin。 com/3ajvcc7u

I've run into a issue with jQuery becoming undefined in a for loop. I have found a solution, but I'm trying to understand why the issue occurs. Of course, I'm open to feedback on my programming style and choices. Anyway I digress...

Background

Working on a bookmarklet to automate a tedious task in a asset management system that's done in the browser. There are a million and one better ways that I would like to do this, but due to technical and political constrains, cannot.

The task being automated is long and has to be repeated numerous times so it must be non-blocking so the DOM can be updated with a progress bar.

Issue

The below code works fine for a single iteration. However, on the successive iteration, jQuery becomes undefined which causes the code to crash since jQuery is required in UI_ProgressBar.

After UI_Render completes, $ becomes undefined however I have no clue why this might be the case.

async function UI_Render()
{
    return new Promise(resolve => setTimeout(resolve, 10)); 
}

//i = [0,100] is for the example.
for(let i = 0; i <= 100; i++)
{
    await DoStuff(i);
    await UI_ProgressBar(i).then(async function () {
        await UI_Render();
    });
}

Interim Solution

Currently my interim solution is to use a temporary variable to hold jQuery but this is not ideal.

async function UI_Render(){
    let v = $;
    var p = new Promise(resolve => setTimeout(resolve, 10)); 
    $ = v;
    return p; 
}

If you want to test the code, here is a raw extract that can be pasted into the developer console: https://pastebin.com/3Ajvcc7u

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文