如何使工厂内的未来同步化?我要在这里向客户返回null。
factory Project.retrieve(String hash, CompetencesService service) {
Project project;
service.dbRef.child("project").once("value").then((snapshot) {
Map val = snapshot.val();
project = toObservable(new Project.fromJson(val));
if(project != null) {
project.listen(service);
print("listening1");
} else {
project = toObservable(new Project.newHash(hash));
service.dbRef.child("project").update(project.toJson()).then((error) {
if(error) {
//
} else {
project.listen(service);
print("listening2");
}
});
}
});
return project;
}有人为这个已询问,但我正在寻找解决办法的例子。
发布于 2015-07-02 05:31:05
目前无法创建异步构造函数或工厂,也无法同步等待Future。
后者有一个明显的原因:如果您将停止并同步等待来自当前隔离本身的东西(而不是文件I/O等外部事件),它将永远不会发生,因为Isolate处于一个处于等待状态的单个线程中。
因此,这里唯一的方法是让静态方法返回带有Future实例的Project,就像您提供的链接中提到的那样:
static Future<Project> retrieve() async {
var snapshot = await service.dbRef.child("project").once("value");
Project project = toObservable(new Project.fromJson(snapshot.val()));
...
return project; // Note you're actually returning a Future here
}发布于 2015-07-04 14:01:37
我尝试实现Future接口,然后工厂和构造函数可以返回一个Future,并且可以是await。
@proxy
class AsyncFact implements Future {
factory AsyncFact() {
return new AsyncFact._internal(new Future.delayed(
const Duration(seconds: 1), () => '[Expensive Instance]'));
}
AsyncFact._internal(o) : _mirror = reflect(o);
final InstanceMirror _mirror;
@override
noSuchMethod(Invocation invocation) => _mirror.delegate(invocation);
}
@proxy
class AsyncConst implements Future {
AsyncConst() : _mirror = reflect(new Future.delayed(
const Duration(seconds: 1), () => '[Expensive Instance]'));
final InstanceMirror _mirror;
@override
noSuchMethod(Invocation invocation) => _mirror.delegate(invocation);
}
main() async {
print(await new AsyncFact()); // [Expensive Instance]
print(await new AsyncConst()); // [Expensive Instance]
}https://stackoverflow.com/questions/31172092
复制相似问题