Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

asynchronous - async is snowballing to callers, can't make constructor async

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

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

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

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);
}

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

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

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.

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

async/await is only syntactic sugar for methodThatReturnsFuture().then(...)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...