异步对调用者来说是滚雪球,不能使构造函数异步 [英] async is snowballing to callers, can't make constructor async

查看:20
本文介绍了异步对调用者来说是滚雪球,不能使构造函数异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 loadData 可以从文件中加载一些文本:

I have a function loadData that loads some text from a file:

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/data/entities.json');
}

loadString 方法来自 Flutter SDK,是异步的.

The loadString method is from Flutter SDK, and is asynchronous.

然后在另一个方法中调用 loadAsset 方法,我必须将其标记为 async,因为 loadAsset 是异步的,我需要使用等待:

The loadAsset method is then called in another method, that must me marked as async, since loadAsset is async and I need to use await:

Future<List<Entity>> loadEntities() async {
  String jsonData = await loadAsset();
  return parseData(jsonData);
}

parseData 方法不是异步的,它接收一个 String,解析它,并返回一个对象列表:

The parseData method is not async, it receives a String, parse it, and return a list of objects:

List<Entity> parseData(String jsonString) {
  ...
}

但由于loadEntities必须用async标记,这就要求它返回一个Future,但实际上,它不是一个Future 因为我使用了 await,它等待 loadAsset 方法完成,然后使用结果调用 parseData 函数.

But since loadEntities must be marked with async, this requires that it returns a Future, but in practice, it's not a Future because since I use await, it awaits for the loadAsset method to finish, then call the parseData funcion using the result.

这很容易变成async 调用的滚雪球,因为每个使用loadEntities 的方法也必须标记为async.

This easily turns into a snowball of async call, because every method that uses loadEntities must be marked as async too.

另外,我不能在类构造函数中使用 loadEntities,因为构造函数应该标记为 async,这在 Dart 中是不允许的.

Also, I can't use loadEntities in a class constructor, because the constructor should be marked as async, which is not allowed in Dart.

我是否在 Dart 中使用了 async/await 模式错误?如何在类构造函数中使用 loadEntities 方法?

Am I using the async/await pattern in Dart wrong? How could I use the loadEntities method in a class constructor?

推荐答案

不,异步是会传染的,没有办法从异步返回到同步执行.

No, async is contagious and there is no way to go back from async to sync execution.

async/await 只是 methodThatReturnsFuture().then(...)

使用async 标记方法只是为了让您在其主体内使用await.如果没有 async,您仍然需要返回 Future 以调用代码,以便仅在 loadAsset() 的结果可用后才执行.

Marking a method with async is only to allow you to use await inside its body. Without async you would still need to return a Future for calling code to only execute after the result of loadAsset() becomes available.

这篇关于异步对调用者来说是滚雪球,不能使构造函数异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆