【发布时间】:2016-09-20 22:44:38
【问题描述】:
我已经阅读了几个 stackoverflow 问题、dart 文档,甚至还观看了有关 async 和 await 的视频。我还没有找到我的问题的答案。我想调用一个异步方法,执行其他代码,然后等待异步任务完成。
这是我正在使用的示例。这是我的组件
Credit credit;
...
Future<Null> getCredit(id) async {
try {
credit = await _creditService.getCredit(id);
}
catch (e) {
errorMessage = e.toString();
}
}
...
void onUpdateCredit(int credit_id) {
getCredit(credit_id);
creditDialogTitle = 'Update Credit';
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
此代码崩溃,因为尝试使用它时信用为空。一种解决方法是结合这两种方法:
Future<Null> onUpdateCredit(id) async {
try {
credit = await _creditService.getCredit(id);
creditDialogTitle = 'Update Credit';
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
catch (e) {
errorMessage = e.toString();
}
}
没有什么是并行的,如果我需要代码中其他地方的功劳,我将不得不复制该方法的 try/catch 部分。我也可以这样编码:
void onUpdateCredit(int credit_id) {
credit = null;
getCredit(credit_id);
creditDialogTitle = 'Update Credit';
while (credit == null) {//wait a period of time}
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
在其他情况下,我在我的 html 中使用 *ngIf="var != null" 执行类似的操作,其中 var 由未来填充。
有没有比使用 while (credit == null) 更好的方法?此示例仅在请求和完成之间执行一条指令,因此很简单。我敢肯定,我会在其他情况之间有很多事情要做。我也在添加服务方法:
Future<Credit> getCredit(int id) async {
try {
String url = "http://catbox.loc/credits/${id.toString()}";
HttpRequest response = await HttpRequest.request(
url, requestHeaders: headers);
Map data = JSON.decode(response.responseText);
final credit = new Credit.fromJson(data);
return credit;
}
catch (e) {
throw _handleError(e);
}
}
更新
根据@Douglas 的回答,这是可行的:
Future<Null> onUpdateCredit(id) async {
Future future = getCredit(id);
creditDialogTitle = 'Update Credit';
await future;
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
然后我消除了干预方法。
Future<Null> onUpdateCredit(id) async {
try {
Future<Credit> future = _creditService.getCredit(id);
creditDialogTitle = 'Update Credit';
credit = await future;
creditArtistIndex = credit.artist_id;
instrument = credit.instrument;
creditNotes = credit.notes;
creditDialog.open();
}
catch (e) {
errorMessage = e.toString();
}
}
【问题讨论】:
标签: dart angular-dart