考虑以下异步函数:
async fn call_me<F>(f : F ) -> Result<(), Error>
where F : FnOnce() -> Result<(), Error> {
f()
}
有什么办法可以延迟里面 的执行f()
吗?
std::thread::sleep(std::time::Duration::from_millis(...)
将设置当前线程休眠,tokio::time::delay_for(..)
只能在异步上下文中使用与异步闭包非常相似的是一个返回 a Future
(恰好是一个异步块)的闭包
async fn call_me<F, Fut>(f: F) -> Result<(), ()>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<(), ()>>,
{
f().await
}
#[tokio_macros::main]
async fn main() {
call_me(|| async {
tokio::time::delay_for(std::time::Duration::from_secs(10)).await;
Ok(())
})
.await
.unwrap();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句