Handling Futures

  1. Why asynchronous code matters
  2. Asynchronous operations let your program complete work while waiting for another operation to finish. Here are some common asynchronous operations:

    • Fetching data over a network.

    • Writing to a database.

    • Reading data from a file.

    To perform asynchronous operations in Dart, you can use the Future class and the async and await keywords.

    We call a function asynchronous when it return after setting up a possibly time-consuming operation (such as Input/Output), without waiting for that operation to complete.


  3. Future class
  4. A Future is used to represent a potential value, or error, that will be available at some time in the future. Receivers of a Future can register callbacks that handle the value using .then() or handle the error once it is available using .catchError().

    Example :

      Future<String> result=getResultFromServer()

      result.then((value) => handleValue(value)).catchError((error) => handleError(error));

    A Future can be completed in two ways: with a value ("the future succeeds") or with an error ("the future fails"). We can install callbacks for each case.


  5. Handling Futures with Async and Await
  6. Code that uses async and await is asynchronous, but it looks a lot like synchronous code. For example, here’s some code that uses await to wait for the result of an asynchronous function:

    await lookUpVersion();

    To use await, code must be in an async function ( a function marked as async) :

    Future checkVersion() async {

      var version = await lookUpVersion();

      // Do something with version

    }

    Note:

    Although an async function might perform time-consuming operations, it doesn’t wait for those operations. Instead, the async function executes only until it encounters its first await expression (details). Then it returns a Future object, resuming execution only after the await expression completes.


    It's a good practice to use try, catch and finally handle errors and cleanup in code that uses await:

    try {

      version = await lookUpVersion();

    catch (e) {

      // React to inability to look up the version

    }


    You can use await multiple times in an async function. For example, the following code waits three times for the results of functions:

      var entrypoint = await findEntrypoint();

      var exitCode = await runExecutable(entrypoint, args);

      await flushThenExit(exitCode);


    In await expression, the value of expression is usually a Future; if it isn’t, then the value is automatically wrapped in a Future. This Future object indicates a promise to return an object. The value of await expression is that returned object. The await expression makes execution pause until that object is available.


    If you get a compile-time error when using await, make sure await is in an async function. For example, to use await in your app’s main() function, the body of main() must be marked as async:

    Future main() async {

      checkVersion();

      print('In main: version is ${await lookUpVersion()}');

    }




        If you went to go deeper into this subject : async-await