Home > database >  Clarifying asynchronous operations in dart
Clarifying asynchronous operations in dart

Time:10-29

In the async codelab: Ref: https://dart.dev/codelabs/async-await

They have the following snippet:

Future<void> printOrderMessage() async {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
  print('Your order is: $order');
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex and slow.
  return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}

void main() async {
  countSeconds(4);
  await printOrderMessage();
}

Based on the logic of printOrderMessage() I've made a similar function:

void main() async {
  int? value;
  value = await test();
  print(value);
}

Future<int?> test() async{
  print('Function has started');
  Future.delayed(Duration(milliseconds: 2000), () {
    return 4;
  });
}

In my case, it prints Function has started null. why doesn't it wait for the value to be populated

CodePudding user response:

Future<int?> test() async {
  print('Function has started');
  await Future.delayed(Duration(milliseconds: 2000), () {});
  return 4;
}
Future<int?> test() async {
  print('Function has started');
  return Future.delayed(Duration(milliseconds: 2000), () {
return 4;
});
 
}
  • Related