0
votes

I have a few async functions in my dart program which interact with SQLite database. I use await expression to invoke those functions and mostly the functions are executed when they're awaited on but one function does not execute and the calling function continues execution without awaiting on the called function. Here's the code:

Future<int> addShoppingList(String listName) async {
    var dbClient = await db;
    String now = new DateTime.now().toString();
    await dbClient.transaction((txn) async {
      int res = await txn.rawInsert("insert into lists(list_name,list_created_at) values(\'$listName\',\'$now\')");
      print('result of adding a new shopping list: $res');
      return res;
    });
    List<Map> resList = await dbClient.rawQuery("select list_id from lists where list_name=\'$listName\'");
    if (resList.length > 0) {
      return resList[0]['list_id'];
    }
    return 0;
    //await dbClient.rawInsert("insert into lists(list_name,list_created_at) values(\'$listName\',\'$now\')");
  }

  Future<int> addShoppingListItems(int listId, Map<String,String> listItems) async {
    var dbClient = await db;
    int res = 0;

    listItems.forEach((itemName, quantity) async{
      int itemId = await getItemId(itemName);
      print('adding item $itemName with id $itemId');
      await dbClient.transaction((txn) async {
        res = await txn.rawInsert("insert into list_items values($listId,$itemId,\'$quantity\')");
        print('result of adding item in list_items: $res');
      });
      return res;
    });
    return 0;
  }

  Future<int> addItemsToShoppingList(String listName, Map<String,String> listItems) async {
    int listId = await getListId(listName);
    if (listId == 0) {
      listId = await addShoppingList(listName);
      print('got list id of $listId after adding new list');
    }
    print('in additemstoshoppinglist list id: $listId');
    print('in additemstoshoppinglist  ${listItems.toString()}');
    int res = await addShoppingListItems(listId, listItems);
    print('result after adding item in addItemsToShoppingList: $res');
    return res;
  }

In my external class I await on addItemsToShoppingList function to start the whole chain of functions. When I run the code, I see that the functions getListId(), addShoppingList() are awaited correctly(the execution of addItemsToShoppingList does not proceed until the awaited functions are executed) but when I await on addShoppingListItems, the calling function's execution does not wait until addShoppingListItems returns. What am I missing here and how can I make sure addShoppingListItems returns before the execution of calling function can proceed?

1

1 Answers

0
votes

I figured out that the problem was with the way async functions are awaited upon in the for each loop of the map being used. I solved this problem with the solution given here: Map forEach function exits with an await inside