修改器异步不能通过应用于设置器的主体 [英] The modifier async can not by applied to the body of a setter
问题描述
如果编辑器给出此错误,如何在setter中使用 hashIt
函数
How can I use hashIt
function in setter if editor gives this error
修饰符async不能应用于设置器的主体
The modifier async can not by applied to the body of a setter
Future<String> hashIt(String password) async {
return await PasswordHash.hashStorage(password);
}
set hashPass(String pass) async { // error here
final hash = await hashIt(pass);
_hash = hash;
}
编译器消息:错误:设置者不能使用'async','async *'或'sync *'.
推荐答案
设置器不能 async
的原因是 async
函数返回一个Future,而setter不返回任何东西.这将使设置器 async
变得非常危险,因为设置器中的任何错误都将变为未捕获的异步错误(这可能会导致程序崩溃).另外, async
可能意味着该操作将花费一些时间,但是调用方无法等待该操作完成.这就带来了比赛条件的风险.所以,这是为了保护自己.
The reason a setter cannot be async
is that an async
function returns a future, and a setter does not return anything. That makes it highly dangerous to make a setter async
because any error in the setter will become an uncaught asynchronous error (which may crash your program).
Also, being async
probably means that the operation will take some time, but there is no way for the caller to wait for the operation to complete. That introduces a risk of race conditions.
So, it's for your own protections.
如果您仍然需要在设置器内部执行异步操作,或者在进行实际设置后记录一些操作,则有一些选择.
If you need to do something asynchronous inside the setter anyway, perhaps log something after doing the actual setting, you have a few options.
最简单的方法是只调用 async
辅助函数:
The simplest is to just call an async
helper function:
set foo(Foo foo) {
_foo = foo;
_logSettingFoo(foo);
}
static void _logSettingFoo(Foo foo) async {
try {
var logger = await _getLogger();
await logger.log("set foo", foo);
logger.release(); // or whatever.
} catch (e) {
// report e somehow.
}
}
这很清楚,您正在调用一个异步函数,没有人等待它完成.
This makes it very clear that you are calling an async function where nobody's waiting for it to complete.
如果您不想拥有单独的帮助程序功能,可以内联它:
If you don't want to have a separate helper function, you can inline it:
set foo(Foo foo) {
_foo = foo;
void _logSettingFoo() async {
...
}
_logSettingFoo();
}
甚至
set foo(Foo foo) {
_foo = foo;
() async {
...foo...
}();
}
这篇关于修改器异步不能通过应用于设置器的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!