【发布时间】:2014-12-10 17:58:30
【问题描述】:
我正在尝试在我的应用程序中使用 async/await 模式,因为我不喜欢到处携带 Future。
我想要实现的是这个方法:
Future<Map> loadConfig() {
return Config.loadConfig().then((config) {
// do some assertions in here
});
}
和调用者:
void main() {
Future<Map> config = loadConfig()
.then((config) {
// do complicated stuff, and have other async calls.
app.run(config);
});
}
有没有办法可以使用 async/await 功能使代码更漂亮?我尝试过这样的事情:
Map loadConfig async () {
Map config = await Config.loadConfig();
// do some assertions on config
return config;
}
和调用者:
void main() async {
Map config = await loadConfig();
// do complicated stuff, and have other async calls.
app.run(config);
}
它在loadConfig 方法中告诉我的是type '_Future' is not a subtype of type 'Map' of 'function result'. 好像await something() 的结果返回一个Future<typeOfSomething>... 并不是所有这一切的意义都在某种程度上摆脱了Future 让它看起来像同步代码?
作为旁注,我正在使用
❯ dartanalyzer --version
dartanalyzer version 1.8.3
由于某种原因,它无法识别 async 和 await 关键字/语法。是否有开关告诉它使用异步功能?
编辑:也许我做错了什么,但这是我在@Günter Zöchbauer 回答后测试的结果。
loadConfig() 函数:
Future<Map> loadConfig() {
return Config.loadConfig().then((config) {
assert(config["listeningPort"] != null);
assert(config["gitWorkingDir"] != null);
assert(config["clientPath"] != null);
assert(config["websitePath"] != null);
assert(config["serverPath"] != null);
assert(config["serverFileName"] != null);
assert(config["gitTarget"] != null);
assert(config["clientHostname"] != null);
print("Loaded config successfully");
});
}
还有我的主要调用函数:
Map config = await loadConfig();
if (config == null) {
print("config is null");
}
var patate = loadConfig().then((otherConfig) {
if (otherConfig == null) {
print("other config is null");
}
});
打印出来的
Loaded config successfully
config is null
Loaded config successfully
other config is null
知道为什么吗?
edit2:
正如 Gunter 和 Florian Loitsch 所指出的,我必须像这样编写 loadConfig 函数:
Future<Map> loadConfig() {
return Config.loadConfig().then((config) {
assert(config["listeningPort"] != null);
assert(config["gitWorkingDir"] != null);
assert(config["clientPath"] != null);
assert(config["websitePath"] != null);
assert(config["serverPath"] != null);
assert(config["serverFileName"] != null);
assert(config["gitTarget"] != null);
assert(config["clientHostname"] != null);
print("Loaded config successfully");
return config;
});
}
【问题讨论】:
-
async 只改变函数的主体。您仍在返回地图。你需要loadConfig的
Future返回值:Future<Map> loadConfig() async {。 -
更新版本打印
null,因为您的then函数不返回任何内容。您需要在print("Loaded config successfully")之后的最后一行输入return config。将.then视为期货上的.map(就像List上的.map)。 -
我不知道为什么,但是我们在 Gunter 的回答下进行了一次大讨论,现在已经消失了。不过谢谢!
标签: dart async-await dart-async