typestar

Futures y async/await en Dart

async marca la función; await la pausa a ella, no al programa.

// async marks the function; await pauses it without blocking the
// program's single thread.
Future<String> fetchForecast() async {
  await Future.delayed(const Duration(milliseconds: 50));
  return 'SW 12 kts, clearing';
}

Future<void> main() async {
  print('Requesting forecast...');
  final forecast = await fetchForecast();
  print('Forecast: $forecast');

  // Futures also chain without await.
  await fetchForecast().then((f) => print('Again: $f'));
}

Cómo funciona

  1. Future<String> es un valor que llegará; async habilita await.
  2. await fetchForecast() se lee como código síncrono.
  3. .then encadena el mismo future sin await.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
15
Caracteres a escribir
447
Tokens
87
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 75 segundos.

Escribe este fragmento

Paso 1 de 3 en Async; paso 22 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →