Can Asynchronous Javascript Functions Be Called Synchronously?
While asynchronous programming is common in Javascript, specific scenarios may require synchronous function calls for existing synchronous codebases. Despite acknowledging the suboptimal nature of this approach, it may be necessary to retrofit asynchronous calls into a larger synchronous codebase due to time constraints.
Blocking Callback Functions
The challenge lies in blocking the execution of the calling function until the callback from the asynchronous function is received. Key considerations include:
Example Implementation:
function doSomething() { var data; function callBack(d) { window.data = d; } myAsynchronousCall(param1, callBack); // Start polling var intvl = setInterval(function() { if (window.data) { clearInterval(intvl); console.log(data); } }, 100); }
Refactoring for Asynchronous Compliance:
However, it's worth noting that the ideal approach remains to modify the calling function and pass a callback to handle the asynchronous operation. This maintains asynchronous integrity without sacrificing synchronous codebase functionality.
function doSomething(func) { function callBack(d) { func(d); } myAsynchronousCall(param1, callBack); } doSomething(function(data) { console.log(data); });
The above is the detailed content of Can Asynchronous JavaScript Functions Be Forced to Execute Synchronously?. For more information, please follow other related articles on the PHP Chinese website!