我正在尝试在我的应用程序中使用 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
知道为什么吗?
编辑2:
正如 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;
});
}
您无需更改loadConfig
函数。应用于main()
的更改应该执行。