Harsh Bhudolia
Harsh Bhudolia

Reputation: 153

async and await in Dart

When I use async function and then the await keyword, does the code execution stops till await is resolved or do they take the next line of code(or block of code) as .then and continue executing the rest as usual?

Future<void> deleteProduct(String id) async {
    final url = Uri.parse(
        'https://my-shop-38f1d-default-rtdb.firebaseio.com/products/$id.json?auth=$authToken');
    final existingProductIndex = _items.indexWhere((prod) => prod.id == id);
    var existingProduct = _items[existingProductIndex];
    _items.removeAt(existingProductIndex);
    notifyListeners();
    final response = await http.delete(url);
    if (response.statusCode >= 400) {
      items.insert(existingProductIndex, existingProduct);

      notifyListeners();
      throw HttpException('Could Not Delete Product');
    }
  }

For example does the execution stops as await http.delete... till it is resolved or the if statement block is considered wrapped in .then statement waiting for the await function while the rest works as it should be?

Upvotes: 3

Views: 642

Answers (2)

jamesdlin
jamesdlin

Reputation: 90175

await is syntactic sugar for creating a Future.then callback (and potentially other completion callbacks). await therefore provides the appearance of pausing execution in your async function, but your program will return to Dart's event loop and continue executing other code.

Upvotes: 0

BLKKKBVSIK
BLKKKBVSIK

Reputation: 3566

Basically, it actually waits until your Future is resolved.

You can checkout best practices and documentation about async/await keyword on the official documentation: https://dart.dev/codelabs/async-await

Upvotes: 2

Related Questions