等待外部JS功能,然后继续使用相同的方法
我有一个简单的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()
结束之前被调用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
制作
firstFunction()
返回承诺。制作
mySecondunction
aysnc。这就是我建议您执行此操作的方式,因为AJAX请求不会阻止其他代码的执行,例如按钮回调。异步/等待和承诺起初很难掌握,因此,这里有一些关于它们在幕后工作方式的阅读。
Make
firstFunction()
return a promise.Make
mySecondFunction
aysnc.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
只需使用 时, 循环就更改
,然后在该循环中调用
firstFunction
。例子:
Just change your
if
clauses with awhile
loop and call yourfirstFunction
in that loop.Example: