简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM