等待外部JS功能,然后继续使用相同的方法

发布于 2025-01-31 02:21:52 字数 1238 浏览 2 评论 0 原文

我有一个简单的JS函数,如下所示:

function firstFunction() {
    $.ajax({
        url: "/path/to/my/endpoint",
        type: "GET"
    }).done(function (data) {
        localStorage.setItem("myItem", data);
    });
}

以后,我有一个这样定义的函数:

function mySecondFunction() {
    if(localStorage.getItem("myItem") == null) {
        // Here I want to call firstFunction() and stop everything until it finishes
    }

    //Immediately use localStorage.getItem("myItem") for other purposes
    //no matter I entered the if() or not
}

使用一个简单的 async:false in $。$。ajax ,它有效,但是我已经看到它将被弃用,我想避免使用此解决方案

您能否建议如何在输入我的时等待 mySecondfunction 如果()

我尝试了 $。当() n时,但没有成功,也许我做了一些错误?

我尝试了类似的东西

   function mySecondFunction() {
      var deferred = $.Deferred();

      if(localStorage.getItem("myItem") == null) {
           $.when(firstFunction()).then(function () {
                    deferred.resolve();
                })
      }
      else {
         deferred.resolve();
      }

      //other instructions
    }

,但是其他说明 firstFunction()结束之前被调用。

I have a simple JS function defined like this :

function firstFunction() {
    $.ajax({
        url: "/path/to/my/endpoint",
        type: "GET"
    }).done(function (data) {
        localStorage.setItem("myItem", data);
    });
}

Later on, I have another function defined like this :

function mySecondFunction() {
    if(localStorage.getItem("myItem") == null) {
        // Here I want to call firstFunction() and stop everything until it finishes
    }

    //Immediately use localStorage.getItem("myItem") for other purposes
    //no matter I entered the if() or not
}

With a simple async: false in $.ajax, it works, but I've seen it's going to be deprecated and I want to avoid this solution.

Could you please suggest how to wait for mySecondFunction when entering my if() ?

I tried with $.when() but without success, maybe I did somehting wrong ?

I tried something like

   function mySecondFunction() {
      var deferred = $.Deferred();

      if(localStorage.getItem("myItem") == null) {
           $.when(firstFunction()).then(function () {
                    deferred.resolve();
                })
      }
      else {
         deferred.resolve();
      }

      //other instructions
    }

But other instructions are called BEFORE the end of firstFunction()

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘初心 2025-02-07 02:21:52

制作 firstFunction()返回承诺。

function firstFunction() {
    return new Promise((res, err) => {
        $.ajax({
            url: "/path/to/my/endpoint",
            type: "GET"
        }).done(function (data) {
            localStorage.setItem("myItem", data);
            res()
        });
    });
}

制作 mySecondunction aysnc。

async function mySecondFunction() {
    if(localStorage.getItem("myItem") == null) {
        await firstFunction();
    }

    localStorage.getItem("myItem")
    ...
}

这就是我建议您执行此操作的方式,因为AJAX请求不会阻止其他代码的执行,例如按钮回调。异步/等待和承诺起初很难掌握,因此,这里有一些关于它们在幕后工作方式的阅读。


Make firstFunction() return a promise.

function firstFunction() {
    return new Promise((res, err) => {
        $.ajax({
            url: "/path/to/my/endpoint",
            type: "GET"
        }).done(function (data) {
            localStorage.setItem("myItem", data);
            res()
        });
    });
}

Make mySecondFunction aysnc.

async function mySecondFunction() {
    if(localStorage.getItem("myItem") == null) {
        await firstFunction();
    }

    localStorage.getItem("myItem")
    ...
}

This is how I would recommend you do this, since the ajax request wont block execution of other code, like button callbacks. Async/await and promises are hard to grasp at first, so here's some reading on how they work behind the scenes.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

救星 2025-02-07 02:21:52

只需使用 时, 循环就更改,然后在该循​​环中调用 firstFunction

例子:

function mySecondFunction() {
    while(localStorage.getItem("myItem") == null) {
        firstFunction()
    }
}

Just change your if clauses with a while loop and call your firstFunction in that loop.

Example:

function mySecondFunction() {
    while(localStorage.getItem("myItem") == null) {
        firstFunction()
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文