可以用Dart语言编写类似的代码吗?
int i;
try {
i = await getResultAsync();
} catch(exception) {
// Do something
}
Run Code Online (Sandbox Code Playgroud) 如何立即获得Future的结果?例如:
void main() {
Process.run('some_shell_command', []).then((ProcessResult result) {
print(result.stdout); // I have the output here...
});
// ... but want it here.
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Dart 中制作一个简单的 RPG。我需要在 div 的屏幕上显示文本,并且我需要让程序在显示下一段文本之前等待用户输入。
例如:
void main() {
showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
print("showText has finished");
}
Run Code Online (Sandbox Code Playgroud)
"showText has finished"在显示文本并且玩家按下回车键之前不应显示。这是我到目前为止的(在我看来很丑陋)代码:
void showText(String text) {
var textBox = querySelector("#sample_text_id")
..text = "";
var timer;
var out;
out = ([int i = 0]) {
textBox.text += text[i];
if (i < text.length - 1) timer = new Timer(const Duration(milliseconds: 10), () => out(i + 1));
};
out();
}
Run Code Online (Sandbox Code Playgroud)
Timerout()异步运行该函数,我不希望它这样做。理想情况下,我想写这样的东西:
void showText(String …Run Code Online (Sandbox Code Playgroud) import 'dart:async';
void main() {
divide(1, 0).then((result) => print('1 / 0 = $result'))
.catchError((error) => print('Error occured during division: $error'));
}
Future<double> divide(int a, b) {
if (b == 0) {
throw new Exception('Division by zero');
}
return new Future.value(a/b);
}
Run Code Online (Sandbox Code Playgroud)
目前我正在学习如何在 Dart 中使用 future,并且我陷入了这样一个简单的例子中。当用户尝试执行除以零时,我的未来会抛出异常。但是, .catchError 不处理我的异常。我得到了未处理的异常,并带有堆栈跟踪。我很确定我错过了一些明显的东西,但无法理解到底是什么。
据我了解,还有另一种方法来处理错误:
divide(1, 0).then((result) => print('1 / 0 = $result'),
onError: (error) => print('Error occured during division: $error'));
Run Code Online (Sandbox Code Playgroud)
使用命名可选参数 - onError。这样做仍然会导致未处理的异常。
我还想澄清一件事。我对吗?- 这两种方法之间的唯一区别是 .catchError() 还处理内部 future 抛出的错误(在外部 future 的 then() 方法内部调用的 future),而 onError …