Mirza Celik
Mirza Celik

Reputation: 53

Dart async await with a future

I have a situation where a map method is not completing before a return statement in a future list.

Here is the code below. The line that prints "####### returnFormFields----" prints first and then the map runs. How can I make sure the map is done before returning me the data. Any help is greatly appreciated!

 void callFetchForms() async {

  var tempFormFields = [1, 2, 3, 4, 5];

  var tempFormFields2;

  tempFormFields2 = await get_select_system_field_data(tempFormFields);

  print("-----After response : tempFormFields2-------");
  print(tempFormFields2);
}

Future<List<dynamic>> get_select_system_field_data(tempFormFields) async {

var returnFormFields = await tempFormFields.map((fieldData) async {
  print(fieldData);
  
   final response = await http
  .get(Uri.parse('https://jsonplaceholder.typicode.com/users/${fieldData}'));

  if (response.statusCode == 200) {
    var returnData = await jsonDecode(response.body);
    print("Return data for ${fieldData}");
    print(returnData);
  } else {
    printWarning("Error in Response");
  }      

  return fieldData;
}).toList();

print("#############  returnFormFields------");
print(returnFormFields);
print(returnFormFields.runtimeType);

return returnFormFields;
}

Upvotes: 2

Views: 4911

Answers (1)

Michael Horn
Michael Horn

Reputation: 4089

Since map always returns a List, not a Future, await has no effect, and the function simply immediately returns a List<Future>, and none of the individual Futures are awaited.

In order to await all of the futures, you can use Future.wait:

final formFieldFutures = tempFormFields.map((fieldData) async {
    // ...
});

final returnFormFields = await Future.wait(formFieldFutures);

print("#############  returnFormFields------");
print(returnFormFields);
print(returnFormFields.runtimeType);

Upvotes: 1

Related Questions