Warning
This post was published 109 days ago. The information described in this article may have changed.
for code like this:
impl Drop for User {
fn drop(&mut self) {
[...]
if self.dirty {
self.save_when_exit();
}
[...]
}
}
while save_when_exit has to be async fn because it will call sqlx;
At first, I tried
#[tokio::main(flavor = "current_thread")]
async fn save_when_exit(&self) {
_ = storage::save_user_attributes(...)
.await;
}
But turns out it's not allowed by panic:
Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous task
So, I stucked because it is impossible for drop to be a async function.
Seems there is no way out except I rename drop to some_function and calls it manually, Or spawn a new thread to execute the async function;
Both are not good, I think, because the User is created in a async fn like that
async fn xxx() {
let u = User([...]);
drop(u);
}
ideally, I want something like
async fn xxx() {
let u = User([...]);
// the compiler do the following impicitly
// drop(u).await;
}
4 posts - 3 participants
🏷️ rust_feed