如果你有一个像这样的 future 链(取自 Dart 教程)
expensiveA().then((aValue) => expensiveB())
.then((bValue) => expensiveC())
.then((cValue) => doSomethingWith(cValue));
Run Code Online (Sandbox Code Playgroud)
取消这样一条链的正确“Dart”方式是什么?例如,这条长链可能已经在不久前开始,并且您希望在用户采取的操作导致最终结果无用时能够取消它。
expensiveA可以使用、 、的代码expensiveB,expensiveC检查doSomethingWith变量值并在该值具有特定值时抛出错误。
但是有没有通用的方法来杀死一条期货链呢?
dart 教程给出了如何链接 futures 的示例:https://www.dartlang.org/docs/tutorials/futures/#calling-multiple-funcs
关于如何取消 future,有一个问题(恕我直言)得到了部分回答:有没有办法取消 dart Future?
不可以。没有办法取消这样的链条。
不过,有一些方法可以模拟可取消的期货:
var someBool;
cancelIfSomeBoolIsSet(fun(x)) {
return (x) {
if (someBool) return new Completer().future;
return fun(x);
};
}
expensiveA().then(cancelIfSomeBoolIsSet(expensiveB))
.then(cancelIfSomeBoolIsSet(expensiveC))
.then(doSomethingWithCValue);
Run Code Online (Sandbox Code Playgroud)
一旦someBool设置,未来链就被有效地取消,因为完成者的未来永远不会完成。
注意:cancelIfSomeBoolIsSet在我的示例中采用 one-arg 函数(与第一篇文章中的 0-arg 函数相反)。调整代码很简单。
| 归档时间: |
|
| 查看次数: |
802 次 |
| 最近记录: |