【问题标题】:async and await in DartDart 中的异步和等待
【发布时间】:2021-10-04 10:42:49
【问题描述】:

当我使用 async 函数然后使用 await 关键字时,代码执行会停止直到 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 函数,而其余的则按应有的方式工作?

【问题讨论】:

标签: flutter dart


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    await 是用于创建Future.then 回调(以及可能的其他完成回调)的语法糖。因此,await 在您的async 函数中提供了暂停执行的外观,但您的程序将返回到 Dart 的事件循环并继续执行其他代码。

    【讨论】:

      猜你喜欢
      • 2017-12-11
      • 2020-01-14
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 2023-03-10
      • 2017-07-16
      相关资源
      最近更新 更多