Home > front end >  Asynchronous programming in Dart isnt Working
Asynchronous programming in Dart isnt Working

Time:12-01

I have a code in Dart like this:

Future<void> dataProcessAsync() async {
    await Future.delayed(Duration(seconds: 2));
    print("Process Completed!");
}

void main() {
    print("Process 1");
    print("Process 2");
    dataProcessAsync();
    print("Process 3");
    print("Process 4");
}

Everything works fine and asynchronously. The result is as expected (Process 1 - Process 2 - Process 3 - Process 4 - Process Completed!)

But when i write the code like this:

Future<void> dataProcessAsync() async {
    for(int i = 1; i <= 10000000000; i  ){}
    print("Process Completed!");
}

void main() {
    print("Process 1");
    print("Process 2");
    dataProcessAsync();
    print("Process 3");
    print("Process 4");
}

It doesn't work asynchronously. It waited for the dataProcessAsync() for a quite long time then continue with Process 3. (Process 1 - Process 2 - Process Completed! - Process 3 - Process 4)

Can someone tell me whats going on and how to solve this ?

CodePudding user response:

async methods are running synchronously until the first await. If the method are never reaching an await, it will run to completion and return a Future which is filled synchronously.

This is by design and described on the Dart webpage:

An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.

https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await

  • Related