I wish to implement the following logic.
movieSetter(String query)async{
Map m1 = await searchByText(query);
List l1 = m1["Search"];
List finalResult = [];
l1.forEach((element)async{
String imdbID = element["imdbID"];
final res = await searchByID(imdbID);
Movie m1 = Movie.fromJSON(res);
finalResult.add(m1);
});
return finalResult.
}
I want the async code for searchByID to run first and then the finalResult variable to be executed. However, the return statement isn't waiting for the async call to complete and is returning the empty initliased list as it is.
Solution 1: croxx5f
movieSetter(String query)async{
Map m1 = await searchByText(query);
List l1 = m1["Search"];
List finalResult = [];
Movie _searchMovie(dynamic element)async {
String imdbID = element["imdbID"];
final res = await searchByID(imdbID);
Movie m1 = Movie.fromJSON(res);
return m1;
}
await Future.wait([
for (final element in m1)
_searchMovie(element)
]);
///The important part is the await before the Future.wait
return finalResult.
}
When calling the for-each method you are indeed making asynchronous calls, but you are not await
ing them in the context of the movieSetter
function.
So you should use the static method Future.wait
which by the way will be called in parallel and not sequentially, so you might get better performance using it. But the most important part is to await
that function , so it you won't return until all futures respond.