首页 > 解决方案 > Dart 中的异步和等待

问题描述

当我使用 async 函数然后使用 await 关键字时,代码执行是否会停止直到等待解决,或者他们是否将下一行代码(或代码块)作为 .then 并继续像往常一样执行其余部分?

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');
    }
  }

例如,执行是否停止为 await http.delete... 直到它被解决或者 if 语句块被认为包含在 .then 语句中等待 await 函数,而其余的则按原样工作?

标签: flutterdart

解决方案


基本上,它实际上会等到您Future解决。

您可以在官方文档中查看有关 async/await 关键字的最佳实践和文档: https ://dart.dev/codelabs/async-await


推荐阅读