Async programming in Dart & JS

Async programming in Dart & JS

Asynchronous Programming:

Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.

An asynchronous model allows multiple things to happen at the same time. When you start an action, your program continues to run. When the action finishes, the program is informed and gets access to the result (for example, the data read from disk or api call).

Computers are asynchronous by design

Asynchronous Programming In Dart

Dart futures run on the event loop, which manages the event queue. As Dart is a single-threaded program just like JS, all the tasks you write end up in the event loop for execution.

Asynchronous operations in Dart can be achieved in two ways:

  1. Using await and async
  2. Using Future API.

Future:

One of the basic implementations of asynchronous coding patterns in Dart is Future. If you are already familiar with JavaScript, Future has the exact same concept with Promise.

Instead of blocking all computation until the result is available, the asynchronous computation immediately returns a Future which will eventually "complete" with the result.

So a future can be in one of 3 states:

Uncompleted: The uncompleted future is waiting for the function’s asynchronous activity to complete or to throw a mistake.

Completed with a value: The completed Future (data) is ready

Completed with an error:?The completed Future with Error/Mistake data

The Future class has a few constructors:

No alt text provided for this image

  • Future.any():?

Returns the result of the first future in [futures] to complete.

It takes the list of futures and return the result of the first future in the futures list to report that it is complete.

Future<T> any<T>(Iterable<Future<T>> futures)
Type: Future<Object> Function(Iterable<Future<Object>>)        

The returned future is completed with the result of the first future in [futures] to report that it is complete, whether it's with a value or an error. The results of all the other futures are discarded.

If [futures] is empty, or if none of its futures complete, the returned future never completes.

Future<int> slowInt() async {
 await Future.delayed(const Duration(seconds: 2)); 
 return 2; 
}

Future<String> delayedString() async { 
 await Future.delayed(const Duration(seconds: 4)); 
 throw Exception('Time has passed'); 
} 

Future<int> fastInt() async { 
 await Future.delayed(const Duration(seconds: 1)); 
 return 3; 
}


void main() async {
final result = await Future.any([slowInt(), delayedString(), fastInt()]);
// The future of fastInt completes first, others are ignored.
 print('Result: $result'); // 3 
}         


Output:
Result: 3        

  • Future.delayed():?

Creates a future that runs its computation after a delay.

The [computation] will be executed after the given [duration] has passed, and the future is completed with the result of the computation.

By default the return type of the delayed() is dynamic and If [computation] is omitted, it will be treated as if [computation] was () => null, and the future will eventually complete with the null value. In that case, [T] must be nullable.

Example:?

In this example Future will wait for 2 seconds then it will execute the computation part and message printed after 2 seconds of delay.

If the duration is 0 or less, it completes no sooner than in the next event-loop iteration, after all microtasks have run.

void main() async {
  Future.delayed(Duration(seconds: 2), 
    () {
        print('This Message will print after 2 seconds')
     }
  )
}        


Output:
This Message will print after 2 seconds        

If the duration is 0 or less, it completes no sooner than in the next event-loop iteration, after all microtasks have run.

Note: Future will complete once you use async/await or .then(), it won’t complete without it.

Continue here

要查看或添加评论,请登录

社区洞察

其他会员也浏览了