0

I have a function which will call a functionin which 2 async functions are called, first to read out the contents of a json file which will be written into a database in second async function.

called function

static Future<int> readJsonFiles() async {
    try {
      final path = await _externalPath;
      Directory dir = Directory('$path/imports/');
      final List<FileSystemEntity> entities = await dir.list().toList();
      final Iterable<File> files = entities.whereType<File>();
      DataAdapter da = new DataAdapter();
      files.forEach((file) async {
        String ext = file.path.split('.').last;
        if (ext == "json") {
          String fileName = file.path.split('/').last;
          if (fileName.startsWith('users_')){ //user json
            final contents = await file.readAsString();
            await da.batchUdate(User.tableName, jsonDecode(contents));
          }
          file.delete();
        }
      });
      return 1;
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

caller

await FileOperation.readJsonFiles();
User usr = await User.findById(u.trim());

My issue is control is returned to caller after

final contents = await file.readAsString();

which in turn checks database for user which is still empty.

How can I prevent control being passed back to caller after the calling first async in called function.

Thanks.

  • The problem is not that `await` is prematurely allowing the caller to resume execution; the problem is that you're using `Iterable.forEach` with an asynchronous callback, and `Iterable.forEach` expects callbacks to complete synchronously. – jamesdlin May 30 '22 at 19:53
  • thanks for your answer, jamesdlin, very helpful, I will check it out. – user1251520 May 30 '22 at 21:55
  • hey jamesdlin, tried your suggestion, Do NOT use .forEach with asynchronous callbacks. Instead, if you want to wait for each asynchronous callback sequentially, just use a normal for loop. The issue seemed to be gone, thanks. – user1251520 May 30 '22 at 22:10

0 Answers0