DART:将来的语法 [英] DART: syntax of future then

查看:386
本文介绍了DART:将来的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解 then()子句的语法。

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

什么是(erg)=>语法上是expr

我想它可能是一个函数,但是

I thougt it could be a function, but

then( callHandler2(erg)

不起作用,错误:

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

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

What´s `onError: (e) => expr"` syntactically?

3。 onError: .catchError(e)变体之间的区别?

3. Is there a difference between the onError: and the .catchError(e) variants?

推荐答案

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

1) The Fat Arrow is syntactic sugar for short anonymous functions. The two functions below are the same:

someFuture(arg).then((erg) => print(erg));
// is the same as
someFuture(arg).then((erg) { return print(erg); });

基本上,粗箭头基本上会自动返回下一个表达式的求值。

Basically the fat arrow basically automatically returns the evaluation of the next expression.

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

If your callHandler2 has the correct signature, you can just pass the function name. The signature being that it accept the number of parameters as the future will pass to the then clause, and returns null/void.

例如,以下操作将起作用:

For instance the following will work:

void callHandler2(someArg) { ... }
// .. elsewhere in the code
someFuture(arg).then(callHandler);

2)参见答案1)。 fat arrow 只是语法糖,等效于:

2) See answer 1). The fat arrow is just syntactic sugar equivalent to:

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

3) catchError 允许您链接一系列期货之后的错误处理。首先,重要的是要了解可以链接 then 调用,因此,<< c $ c> then 调用将返回将来可以链接到另一个然后调用。 catchError 将捕获链中所有 Future 同步和异步的错误。传递 onError 参数只会处理 Future 的错误,该错误是您和您的任何同步代码的一个参数然后块。 then 块中的任何异步代码都不会被捕获。

3) catchError allows you to chain the error handling after a series of futures. First its important to understand that then calls can be chained, so a then call which returns a Future can be chained to another then call. The catchError will catch errors both synchronous and asynchronous from all Futures in the chain. Passing an onError argument will only deal with an error in the Future its an argument for and for any synchronous code in your then block. Any asynchronous code in your then block will remain uncaught.

大多数Dart代码的最新趋势是使用 catchError 并省略 onError 参数。

Recent tendency in most Dart code is to use catchError and omit the onError argument.

这篇关于DART:将来的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆