在JavaScript中,异步代码是使用Promises和async
/await
语法编写的,与Rust类似。通常可以认为可以简单地将其返回(即,当异步函数作为另一个函数的最后一部分执行时)返回并等待Promise是多余的(因此不鼓励):
async function myFn() { /* ... */ }
async function myFn2() {
// do setup work
return await myFn()
// ^ this is not necessary when we can just return the Promise
}
我想知道在Rust中是否也适用类似的模式。我是否应该这样:
pub async fn my_function(
&mut self,
) -> Result<()> {
// do synchronous setup work
self.exec_command(
/* ... */
)
.await
}
或这个:
pub fn my_function(
&mut self,
) -> impl Future<Output = Result<()>> {
// do synchronous setup work
self.exec_command(
/* ... */
)
}
前者对我来说更符合人体工程学,但我怀疑后者可能会更出色。是这样吗
这两个变体之间的语义差异是,在第一个变体中,同步设置代码仅在等待返回的future时才运行,而在第二个变体中,它将在调用函数后立即运行:
let fut = x.my_function();
// in the second variant, the synchronous setup has finished by now
...
let val = fut.await; // in the first variant, it runs here
为了使差异明显,同步设置代码必须具有副作用,并且在调用异步函数和等待它返回的将来之间需要有一个延迟。
除非您有特定的原因立即执行序言,否则请使用异步功能(即第一个变体)。它使函数更具可预测性,并且在重构函数时使以后添加更多等待更加容易。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句