Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't get rust async code to work with promise #79

Closed
FlondorDev opened this issue Jan 24, 2024 · 4 comments
Closed

Can't get rust async code to work with promise #79

FlondorDev opened this issue Jan 24, 2024 · 4 comments

Comments

@FlondorDev
Copy link

hi, i'm trying to use rust async code with js promises but the code stop executing before the promise can deliver a value (this doesn't happen with rust sync code in promise)

main.rs

use serde_json::Value;
use quickjs_runtime::builder::*;
use quickjs_runtime::jsutils::JsError;
use quickjs_runtime::jsutils::Script;

use elasticsearch::{
    auth::Credentials,
    cert::CertificateValidation,
    http::transport::{SingleNodeConnectionPool, TransportBuilder},
    http::Url,
    Elasticsearch,
};
use tokio::runtime::Runtime;

fn client() -> Elasticsearch {
    let credentials = Credentials::Basic("elastic".to_string(), "elastic".to_string());
    let conn_pool = SingleNodeConnectionPool::new(Url::parse("https://localhost:9200").unwrap());
    let transport = TransportBuilder::new(conn_pool)
        .disable_proxy()
        .auth(credentials)
        .cert_validation(CertificateValidation::None)
        .build()
        .unwrap();

    Elasticsearch::new(transport)
}

async fn cat_index() -> Result<Value, JsError> {
    let elastic = client();
    let indexes = elastic
        .indices()
        .get(elasticsearch::indices::IndicesGetParts::Index(&[
            "care_index",
        ]))
        .send()
        .await
        .unwrap();
    let index = indexes.json::<Value>().await.unwrap();
    Ok(index)
}

#[tokio::main]
async fn main() {
    let rt = QuickJsRuntimeBuilder::new().build();
    
    rt.loop_realm(None, |rt, realm| {
        realm
        .install_function(
            &[],
            "cat_elastic",
            |_rt, realm, _this, _args| {
                    realm.create_resolving_promise_async(cat_index(), |realm, value| {
                        realm.serde_value_to_value_adapter(value)
                    })
                },
                0,
            )
            .unwrap();

        realm
            .install_function(
                &[],
                "log",
                |_rt, realm, _this, args| {
                    println!("{:?}", args[0].to_string());
                    realm.create_undefined()
                },
                1,
            )
            .unwrap();

        realm
            .eval(Script::new("", include_str!("../code.js")))
            .unwrap();
    })
    .await;
}

code.js

cat_elastic().then(p => {
    log(p);
})

what am i doing wrong?

P.S: if i use tokio runtime to block_on the async code (removing the promise part) i can get the result, also using create_resolving_promise not the async one and returning a dummy value i can also get the promise to work

@andrieshiemstra
Copy link
Member

Well, i'll look into the code but my first guess is that the runtime is allready dropped when the async code runs.. just for the test, try to add a thread::sleep(Duration::from_secs(1)) after your last .await; in main()

@andrieshiemstra
Copy link
Member

andrieshiemstra commented Jan 24, 2024

yeah, try something like this.... return promise from qjs and await it before exiting async main

use quickjs_runtime::builder::QuickJsRuntimeBuilder;
use quickjs_runtime::jsutils::{JsError, Script};
use quickjs_runtime::values::JsValueFacade;
use serde_json::Value;

async fn cat_index() -> Result<Value, JsError> {
    let value = serde_json::from_str("{\"abc\": \"i'm a obj made rusty\"}").unwrap();
    println!("cat_index running");
    Ok(value)
}

#[tokio::main]
async fn main() {
    println!("Hello, world!");

    let rt = QuickJsRuntimeBuilder::new().build();

    rt.loop_realm(None, |_rt, realm| {
        realm
            .install_function(
                &[],
                "cat_elastic",
                |_rt, realm, _this, _args| {
                    realm.create_resolving_promise_async(cat_index(), |realm, value| {
                        realm.serde_value_to_value_adapter(value)
                    })
                },
                0,
            )
            .unwrap();

        realm
            .install_function(
                &[],
                "log",
                |_rt, realm, _this, args| {
                    println!("{:?}", args[0].to_string());
                    realm.create_undefined()
                },
                1,
            )
            .unwrap();
    })
    .await;

    let promise_jsvf = rt
        .eval(
            None,
            Script::new(
                "promiseMeThis.js",
                r#"
        async function myCode(){
            let res = await cat_elastic();
            return res;
        };
        // eval statement, thus returning the promise
        myCode()
    "#,
            ),
        )
        .await
        .expect("Script failed misserably");

    if let JsValueFacade::JsPromise { cached_promise } = promise_jsvf {
        // of boy oh boy we got a promise
        let resolved_value = cached_promise
            .get_promise_result()
            .await
            .expect("Promise timed out?");

        match resolved_value {
            Ok(prom_resolved) => {
                println!(
                    "Promise resolved to {:?}",
                    prom_resolved
                        .to_json_string()
                        .await
                        .expect("no not so stringable?")
                );
            }
            Err(_prom_rejected) => {
                panic!("Promise was rejected");
            }
        }
    }
}

@andrieshiemstra
Copy link
Member

Ps just for clarity, this doesn't mean you always have to .await promises for them to run or anything, the problem in this case was just that the runtime would be destroyed before the async code ran...

@FlondorDev
Copy link
Author

FlondorDev commented Jan 24, 2024

ok, this last piece of code solved my issue

if let JsValueFacade::JsPromise { cached_promise } = promise_jsvf {
        // of boy oh boy we got a promise
        let resolved_value = cached_promise
            .get_promise_result()
            .await
            .expect("Promise timed out?");

        match resolved_value {
            Ok(prom_resolved) => {
                println!(
                    "Promise resolved to {:?}",
                    prom_resolved
                        .to_json_string()
                        .await
                        .expect("no not so stringable?")
                );
            }
            Err(_prom_rejected) => {
                panic!("Promise was rejected");
            }
        }
    }

basically yeah the code execution dropped before promise completion, i searched for a while a way to wait for the promise to end but i found the docs a bit lacking

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants