I'm interacting with a third-party JavaScript library where some function calls are asynchronous. Instead of working the asynchronous logic into my application, I preferred to write synchronous wrappers to those async calls. I know, I know, it's terrible design, but this is a demo project with very high chance of being rewritten entirely. I need something to show the team the concept, not really having to worry performance, yet.
Here's what I wanna do:
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {value = result;} );
return value;
}
I tried the jQuery's deferred and promise but it seems to be aiming at the async design pattern. I want to use the synchronous pattern in my code.
-
You cannot make a synchronous wrapper for an async task. Use the deferred/promise pattern!Bergi– Bergi2013年09月10日 23:29:53 +00:00Commented Sep 10, 2013 at 23:29
-
2possible duplicate of How to return the response from an asynchronous call?Liam– Liam2015年07月28日 10:51:48 +00:00Commented Jul 28, 2015 at 10:51
3 Answers 3
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
function f(input, callback) {
var value;
// Assume the async call always succeed
async_call(input, function(result) { callback(result) };
}
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
4 Comments
sync and async anyway? The point is that the user is doing an async call with the callback expecting it to resolve in the scope of the original function. My very simple and naive piece of code adds a callback to his original function and stops the processing of the var value in the end of the function.How about calling a function from within your callback instead of returning a value in sync_call()?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}
2 Comments
Here is a working example of how:-
function testAsync(){
return new Promise((resolve,reject)=>{
//here our function should be implemented
setTimeout(()=>{
console.log("Hello from inside the testAsync function");
resolve();
;} , 5000
);
});
}
async function callerFun(){
console.log("Caller");
await testAsync();
console.log("After waiting");
}
callerFun();
Outputs:
Caller
Hello from inside the testAsync function
After waiting
To make it more complete, error handling should be added (deal with the reject() case).
See here for other examples: https://www.delftstack.com/howto/javascript/javascript-wait-for-function-to-finish/