What does async/await mean in synchronous programing?

Saptadeep Dutta
2 min readJun 25, 2022

[No code. Easy read.]

Brief: await means wait until the statement finishes execution before moving ahead awaits are nested within callable blocks marked async. That’s it! Scroll down for the longer rundown...

Longer narrative:

>First, the context:

Runtimes of JavaScript and Dart execute statements serially. JavaScript and Dart are both single-threaded programming languages. [V8 engine can mimic multithreading, probably by spawning sub-tasks and multiple processes aka worker-threads].

>Left unhandled, this will invariably lead to applications freezing up when long-running tasks are executing.

To resolve use the async/await pattern. The async keyword marks a callable block that has statements that you want to run in background, while you want the system to keep progressing. For example making multiple Http requests.

>Left as is, this behavior can lead to another issue, that of runtime slipping ahead without having the result!

Say, in a mobile app, you want to display the map of the user’s location, but for that first you will need permission to read user’s location data. Right?

Now if you nest the call to obtain user’s permission within an async block, the UI controller will display the Permission’s Dialog and proceed to load the map without waiting for user input and will obviously fail. Because by nesting it within the async block, this is what you indicated the system to do.

>Solution:

Since the result of the dialog box is critical for the next step so you need to prefix await just at the point of calling ObtainUserPermisisonDialog(){…}. This makes the runtime wait up at the Permission’s Dialog step until it receives an input from user…basically halt execution until complete.

>In typed languages, if you need to return values from async callables, the returns type should be Promise<T>. Example: if returning a String from an async callable, the return type would be Promise<String>.

What are Promises?

Think of promises as stubs: Half baked instances, that will get baked (or fail) eventually.

What’s the relevance? await works only with promises and all awaited calls must be within async blocks.

Also note that all statements cannot be awaited.

For example await print(……) won’t work.

>Promises are called Futures in Dart.

>Note: Chained .thens also fit in this scenario, but that’s a different approach altogether.

--

--