Future

Dart에서는 async operation의 결과를 Future로 나타낸다.

이름에서도 느껴지듯이 미래 어떤 시점에 사용 가능한 값 또는 error를 나타내는 데 사용한다.

Future는 uncompleted , completed 두 가지 상태가 있다.

Future<void> fetchUserOrder() {
  // Imagine that this function is fetching user info from another service or database.
  return Future.delayed(Duration(seconds: 2), () => print('Large Latte'));
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}

//https://dart.dev/codelabs/async-await#example-introducing-futures

handle completed value

then() 함수를 통해서 future가 완료되었을 때 실행할 callback을 등록할 수 있다.

Future<int> successor = future.then((int value) {
    // Invoked when the future is completed with a value.
    return 42;  // The successor is completed with the value 42.
  },
  onError: (e) {
    // Invoked when the future is completed with an error.
    if (canHandle(e)) {
      return 499;  // The successor is completed with the value 499.
    } else {
      throw e;  // The successor is completed with the error e.
    }
  });
//then에서 return한 error를 처리하지못하면 catchError에서 처리가능, 더 readabiltiy가 좋다.
Future<int> future = getFuture();
future.then((value) => handleValue(value))
      .catchError((error) => handleError(error));

Similar to the synchronous code, the error handler (registered with catchError) is handling any errors thrown by either foo or bar. If the error-handler had been registered as the onError parameter of the then call, it would not catch errors from the bar call.

만약 catchError나 onError 처럼 error handler가 없다면 error를 uncaught-error handler로 포워딩한다.

여러 개의 future handling