Writing Asynchronous Code

Ever felt like you had all the instructions in place but, for some unknown reason your program was not doing what you expected it to do, or it was acting weird? Well, we’ve all been there and will probably be there, again. In this short article, I’ll briefly explain/talk about why we should make use of asynchronous code as well as its importance.

 

First Things First, What is Asynchronous?

 

In its simplest terms, “Asynchronous refers to something not occurring at the same time as another thing.”

The opposite of asynchronous is synchronous, which means “occurring at the same time” or “simultaneous”.

 

Cool! Let’s get into it then

 

Imagine a field with nothing but beautiful green grass, You, a floating dartboard🎯 in front of you, and the darts in your hands. Once there, you throw a dart to the dartboard and, assuming everything went well, here’s what essentially happened:

 

  1. A dart was grabbed
  2. It was aligned to the target
  3. It was thrown
  4. It traveled through space and time (probably spinning too)
  5. It arrived at the destination
  6. Hit the target and
  7. Lastly, you scored points, right? 

 

Notice how we are being mindful about everything and that there is a sequence of events and some cannot/should not happen before the other?

 

“Yeah, and why?”, you may ask.

 

Well, that’s because we need to understand what exactly is happening or will happen so that we prepare the right solutions, write code that actually does what we intended to, and additionally because anything can happen anytime, hence we need to be ready to handles those cases too.

A very good situation/example that this maps to is making a request to an API or Database where:

 

  • Steps 1, 2, and 3: That’s us getting our methods and API in place and making/sending the request.
  • Steps 4 and 5: The waiting period and the server actually receiving it.
  • Step 6: The execution or the processing of the request.
  • Step 7: Lastly some more waiting and getting our result in form of data or error.

 

Broken Example

 

In the example below, we have 2 functions outside of the main function that we want to execute. What we are hoping is that they are executed one after the other in the specified order.

Expected Result

				
					fun1 completed after 3s delay
exit fun1
fun2 completed after 2s delay
exit fun2
				
			

From

				
					void main() {
  fun1();
  fun2();
}

void fun1() {
  Future.delayed(const Duration(seconds: 3), () {
    print('fun1 completed after 3s delay');
  });
  print('exit fun1');
}

void fun2() {
  Future.delayed(const Duration(seconds: 2), () {
    print('fun2 completed after 2s delay');
  });
  print('exit fun2');
}

				
			

Try running on dartpad.

Result after running, and oops!

				
					exit fun1
exit fun2
fun 2 completed after 2s delay
fun 1 completed after 3s delay
				
			

Well, it did exactly what we told it to do and we didn’t write anything to mention that it should wait before proceeding on to the next function so, by default, it ran synchronously, not asynchronously. In other cases, this would be like making a request and trying to do something with the data before it was fetched.

 

Fixed Example

 

Here what we did was, Turn our functions into futures, and use the async & await keywords, which you can read more about here.

				
					Future<void> main() async {
  await fun1();
  await fun2();
}

Future<void> fun1() async {
  await Future.delayed(const Duration(seconds: 3), () {
    print('fun1 completed after 3s delay');
  });
  print('exit fun1');
}

Future<void> fun2() async {
  await Future.delayed(const Duration(seconds: 2), () {
    print('fun2 completed after 2s delay');
  });
  print('exit fun2');
}

				
			

Result 🥳🎯

				
					fun1 completed after 3s delay
exit fun1
fun2 completed after 2s delay
exit fun2
				
			

Takeaways

 

So, what are the thing we should keep in mind when performing operations that return a result we depend on and, might take time?

 

  1. Always make use of asynchronous functions and await the result.
  2. Make use of try catch (which is something didn’t include in these simple examples).

In the next post, we’ll focus more on the application of try catch when making requests to a server, a fake server 🤭, but it will do the job.

Leave a comment