0

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 ?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.