Waiting for Futures raised by other Futures

♀尐吖头ヾ 提交于 2019-12-20 02:06:52

问题


I'm using the Lawndart library to access browser data, and want to collect the results of a set of queries. Here's what I thought should work:

  numberOfRecordsPerSection(callback) {
    var map = new Map();

    db_sections.keys().forEach((_key) {
      db_sections.getByKey(_key).then((Map _section) {
        int count = _section.length;
        map[_key] = count;
      });
    }).then(callback(map));
  }

However, when the callback is called, map is still empty (it gets populated correctly, but later, after all the Futures have completed). I assume the problem is that the Futures created by the getByKey() calls are not "captured by" the Futures created by the forEach() calls.

How can I correct my code to capture the result correctly?


回答1:


the code from How do I do this jquery pattern in dart? looks very similar to yours

For each entry of _db.keys() a future is added to an array and then waited for all of them being finished by Future.wait()

Not sure if this code works (see comments on the answer on the linked question)

void fnA() {
    fnB().then((_) {
        // Here, all keys should have been loaded
    });
}

Future fnB() {
  return _db.open().then((_) {
    List<Future> futures = [];
    return _db.keys().forEach((String key_name) { 
      futures.add(_db.getByKey(key_name).then((String data) {
        // do something with data
        return data;
      }));
    }).then((_) => Future.wait(futures));
  });
}


来源:https://stackoverflow.com/questions/23969680/waiting-for-futures-raised-by-other-futures

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!