Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Async/await works from main but not from other functions
sorry that not all code is showing up as code, I don't know how to get it to.
Anyway, my issue is as follows:
When I call an async function from main, it works as expected to add a row to my database. Here is my main code:
#[async_std::main]
async fn main() {
add_user_to_database("test".to_string(), "test".to_string(), "test".to_string(), "test".to_string()).await;
let _ = listen(address_and_port);
}
however, when I try to call this async function from a non-main function:
pub fn server_register(stream: TcpStream, traffic: Vec<String>) {
println!("here server registration");
let username = traffic[1].clone();
let pub_rsa_key = traffic[2].clone();
let pub_dsa_key = traffic[3].clone();
let pub_ntru_key = traffic[4].clone();
println!("{:?}", pub_rsa_key);
async { add_user_to_database(username, pub_rsa_key, pub_dsa_key, pub_ntru_key).await};
println!("made it here");
}
it prints my rsa pubkey and the "made it here" string, but completely ignores the async block calling the database function.
async fn add_user_to_database(username: String, pub_rsa_key: String, pub_dsa_key: String, pub_ntru_key: String) -> Result<(), sqlx::Error> {
println!("add user");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect("postgres://username:password@localhost/postgres_db").await?;
sqlx::query_as("INSERT INTO users (
Values(
$1,
$2,
$3,
$4,
$5
)
);")
.bind(1)
.bind(username)
.bind(pub_rsa_key)
.bind(pub_dsa_key)
.bind(pub_ntru_key)
.fetch_one(&pool).await?;
Ok(())
}
I have tried numerous things to get this working, but cannot figure out why the add_user_to_database function is never executed from the server_register() function. It never prints "add user", and no database row is added. When I do it from the main function, it works as expected and adds a row to the database.
3 posts - 3 participants
🏷️ Rust_feed