等待由其他期货提出的期货 [英] Waiting for Futures raised by other Futures
问题描述
我使用Lawndart库来访问浏览器数据,并且想要收集一组查询的结果。这是我认为应该工作:
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));
}
$ b 仍然为空(它正确填充,但后来,所有的期货完成后)。我假设问题是由 getByKey()
调用创建的期货不是由 forEach()
调用。
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?
推荐答案
p> 如何在dart中执行此jquery模式?的代码与您的
对于 _db.keys()
的每个条目,将来会被添加到数组,然后等待所有这些未完成的 Future.wait()
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));
});
}
这篇关于等待由其他期货提出的期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!