вторник, 13 апреля 2021 г.

Asynchronous

//Dart is a single-threaded language.
//Future - promise to give you the value later.
void main() {

  //Callbacks
  print('Start'); //1
  Future<int>.delayed(Duration(seconds: 3), () => 7)
      .then(
        (value) => print('Value: $value'), //3
  )
      .catchError(
        (error) => print('Error: $error'),
  )
      .whenComplete(
    //run after value or error
        () => print('Ready!'), //4
  );
  print('End'); //2

  //async-await
  print('Start2'); //synchronous function
  main2(); //asynchronous function - promise to give you the value later.
  print('End2'); //synchronous function

  //try-catch - error handling
  print('Start3');
  main3();
  print('End3');

}

//asynchronous function
Future<void> main2() async {
  final value = await Future<int>.delayed(Duration(seconds: 2), () => 7);
  //the rest of the function won’t run until the future completes
  print('Value2: $value');
  print('Ready2!');
}

//try-catch - error handling
Future<void> main3() async {
  try {
    //throw Exception('error'); //error testing
    final value = await Future<int>.delayed(Duration(seconds: 1), () => 7);
    //the rest of the function won’t run until the future completes
    print('Value3: $value');
  } catch (error) {
    print(error);
  } finally {
    print('Ready3!'); //run after value or error
  }
}

Комментариев нет:

Отправить комментарий