flutter - 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 函数,而其余的则按原样工作?
解决方案
基本上,它实际上会等到您Future
解决。
您可以在官方文档中查看有关 async/await 关键字的最佳实践和文档: https ://dart.dev/codelabs/async-await
推荐阅读
- reactjs - 由于管理子字符串,未经授权的错误代码 403
- php - 中间件干扰会话消息
- nuget - whitesource 是否尊重 nuget.config
- ejabberd - 无法从非本地 ip 在 ejabberd 中注册
- java - SpringBootApplication在子包下找不到bean
- angular - 通过 Angular Renderer2 编辑画布不起作用
- android - 如何取消收集协程StateFlow?
- sql-server - SQL Server 通过分组数据使用多列排序顺序
- python - 为什么幻影js浏览器打不开?
- javascript - 收到新的 Google 表单提交后,如何忽略向具有价值的行发送电子邮件?