Dart中的未来/异步/等待 [英] Future/async/await in Dart

查看:301
本文介绍了Dart中的未来/异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数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是异步的,我需要使用await:

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以来,它就等待方法完成,然后使用结果调用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.

这篇关于Dart中的未来/异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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