简体   繁体   English

等待异步javascript函数返回

[英]wait for async javascript function to return

I am using a function supplied by a third party library. 我正在使用第三方库提供的功能。 This function takes a callback function as a parameter, but I would like to wait for this callback to be called before continuing. 此函数将回调函数作为参数,但我想等待在继续之前调用此回调函数。 Is there a standard / accepted way to do this? 是否有标准/可接受的方式来做到这一点?

I am not sure if this is a possible solution for you but you can achieve the desired result by breaking your code into 2 functions. 我不确定这是否是一个可能的解决方案,但您可以通过将代码分解为2个函数来实现所需的结果。 Suppose this is what you intend to do: 假设这是你打算做的:

Basically this is your original function: 基本上这是你原来的功能:

function origFunc() {

    codeBeforeThirdPartyFunc();
    ThirdPartyFunc(oldCallBackFunc);
    Wait();
    codeAfterCallBackFunc();
}

You can modify the code flow with something like: 您可以使用以下内容修改代码流:

function newFunc() {
    codeBeforeThirdPartyFunc();
    ThirdPartyFunc(newCallBackFunc);
}
function newCallBackFunc() {
  oldCallBackFunc();
  codeAfterCallBackFunc();
}

This will eliminate the wait loop. 这将消除等待循环。 And as far as I know, busy waiting doesn't work in IE (because ? God only knows).. 据我所知,忙碌的等待在IE中不起作用(因为?上帝只知道)..

这是另一种异步加载jQuery的方法,它不依赖于另一个脚本。

I don't know if Sharad's solution would work in all cases (for instance if you function calls are so far chained that you have to pass data as variables instead of parameters). 我不知道Sharad的解决方案是否适用于所有情况(例如,如果您的函数调用到目前为止已被链接,您必须将数据作为变量而不是参数传递)。 Same problem with global variables. 全局变量也有同样的问题。 JavaScript just doesn't have a "wait" ability. JavaScript只是没有“等待”能力。

Although I had a similar problem and with jQuery, I ended up with a MacGyver type solution that gives you tons of control on when javascript functions execute. 虽然我有一个类似的问题和jQuery,我最终得到了一个MacGyver类型的解决方案,让你可以控制javascript函数何时执行。 I just posted it here as an answer to my own question (but I it's an answer that's not checked - look for my username Emile): How to get a variable returned across multiple functions - Javascript/jQuery 我只是在这里发布它作为我自己的问题的答案(但我是一个未经检查的答案 - 查找我的用户名Emile): 如何获得跨多个函数返回的变量 - Javascript / jQuery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM