Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for wrapping an Asynchronous JavaScript function to make it synchronous

I'm working with a JavaScript API where most of the functions are asynchronous. The API is the WebKit JavaScript Database API which is a binding to a subset of functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.

Here's the async call

db.executeSql(sqlStatement, function(result) {
  // do something with result
});

And here's what I'd like to be able to do

var result = dbWrapper.executeSql(sqlStatement);
// do something with result

Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.

Thank you

like image 423
pfeilbr Avatar asked Oct 18 '08 03:10

pfeilbr


People also ask

How do you make a function synchronous in JavaScript?

Async/Await is a new syntax for writing asynchronous code in JavaScript to make asynchronous code behave in a synchronous way. The word async is used before a function that means a function always returns a promise.

Which async pattern is better in JavaScript?

Which Async patterns should we use? For simple projects, callbacks are the simplest and easier way to handle async flows. On bigger projects with a proper setup, I would choose the async/await pattern, as the asynchronicity is easy to read, has a natural error handling and there's no pyramid of death.

Does async await make it synchronous?

Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.

Is JavaScript synchronous or asynchronous?

JavaScript is Synchronous Spoiler: at its base, JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.


1 Answers

Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.

You generally* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled.

So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation.

*: except in some obscure situations which wouldn't help you and are generally considered bugs

like image 161
bobince Avatar answered Sep 28 '22 18:09

bobince