简体   繁体   English

异步代码运行延迟(Flutter/Dart)

[英]Asynchronous code running late(Flutter/Dart)

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.我希望先运行 searchByID 的异步代码,然后再执行 finalResult 变量。 However, the return statement isn't waiting for the async call to complete and is returning the empty initliased list as it is.但是,return 语句不会等待异步调用完成,而是按原样返回空的初始化列表。

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.当调用 for-each 方法时,您确实在进行异步调用,但您并没有在movieSetter function 的上下文中await它们。

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.所以你应该使用 static 方法Future.wait顺便说一下,它会被并行调用而不是顺序调用,所以你可能会使用它获得更好的性能。 But the most important part is to await that function, so it you won't return until all futures respond.但最重要的部分是await function,因此在所有期货响应之前您不会返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM