DART:未来的语法

mic*_*ica 7 dart dart-async

我不理解该then()条款的语法.

1. myFuture(6).then( (erg) => print(erg) )

What's (erg) => expr语法?

我认为它可能是一个功能,但是

then( callHandler2(erg)
Run Code Online (Sandbox Code Playgroud)

不起作用,错误:

"Multiple markers at this line
- The argument type 'void' cannot be assigned to the parameter type '(String) -> 
 dynamic'
- Undefined name 'erg'
- Expected to find ')'"
Run Code Online (Sandbox Code Playgroud)

2. myFuture(5).then( (erg) { callHandler(erg);}, onError: (e) => print (e)

What´s `onError: (e) => expr"` syntactically?
Run Code Online (Sandbox Code Playgroud)

3.变体onError:.catchError(e)变体之间有区别吗?

Mat*_*t B 11

1)Fat Arrow是短匿名函数的语法糖.以下两个功能是相同的:

someFuture(arg).then((erg) => print(erg));
// is the same as
someFuture(arg).then((erg) { return print(erg); });
Run Code Online (Sandbox Code Playgroud)

基本上胖箭头基本上自动返回下一个表达式的评估.

如果您callHandler2的签名正确,则只需传递函数名称即可.签名是它接受参数的数量,因为将来会传递给then子句,并返回null/void.

例如,以下内容将起作用:

void callHandler2(someArg) { ... }
// .. elsewhere in the code
someFuture(arg).then(callHandler);
Run Code Online (Sandbox Code Playgroud)

2)见答案1).该脂肪箭头只是相当于语法糖:

myFuture(5).then( (erg){ callHandler(erg);}, onError: (e){ print(e); });
Run Code Online (Sandbox Code Playgroud)

3)catchError允许您在一系列期货之后链接错误处理.首先,理解then呼叫可以链接是很重要的,因此then返回a 的呼叫 Future可以链接到另一个then呼叫.在catchError将捕获错误同步和异步所有FutureS IN链.传递onError参数只会处理块中Future任何同步代码的参数中的错误then.您的then块中的任何异步代码都将保持未被捕获状态.

大多数Dart代码最近的趋势是使用catchError和省略onError参数.


小智 6

我将尝试详细说明马特的回答,希望能提供更多见解。

什么then()需要的是一个函数(回调),其签名匹配未来的类型。

例如,给定 aFuture<String> myFuture并且doSomething是任何接受String输入的函数,您可以调用myFuture.then(doSomething). 现在,有几种方法可以定义String在 Dart中接受 a 的函数:

Function(String) doSomething1 = (str) => /* do something with str */  // only one command
Function(String) doSomething2 = (str) { /* do something with str */ } // several commands
Function(String) doSomething3 = myFunction;
myFunction(String) { // Dart will auto imply return type here
  /* do something with str */ // several commands
}
Run Code Online (Sandbox Code Playgroud)

这 3 个函数定义中的任何一个( 的右侧=)都可以进入then(). 前两个定义称为lambda 函数,它们是在运行时创建的,除非您手动复制代码,否则无法重用。Lambda 函数可能会产生类似语言的表达式,即(connection) => connection.connect(). 第三种方法允许重用函数。Lambda 函数在许多语言中都很常见,您可以在此处阅读有关它的更多信息:https : //medium.com/@chineketobenna/lambda-expressions-vs-anonymous-functions-in-javascript-3aa760c958ae

为什么你不能把原因callHandler2(erg)里边then()是因为callHandler2(erg)使用一个未定义的变量erg。使用lambda函数,你就可以告诉then()的是,ergcallHandler2(erg)为未来的产出,所以它知道从哪里得到erg的值。