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

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

问题描述

我有一个函数 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天全站免登陆