Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
Nippysaurus Avatar asked Jun 16 '10 06:06

Nippysaurus


People also ask

How do I wait for async to return?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do you wait for a function to complete?

How to Wait for a Function to Finish in JavaScript. Using a Callback Function With setTimeout() to Wait for a Function to Finish. Using await Keyword and setTimeout() to Wait for a Function to Finish.

How do you wait for a promise to finish before returning the variable of a function?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.


2 Answers

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. 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)..

like image 52
Sharad Avatar answered Oct 26 '22 23:10

Sharad


Here's another method of loading jQuery asynchronously, which doesn't depend on another script.

like image 38
Phil Avatar answered Oct 26 '22 23:10

Phil