Emscripten await operator in C++. Returns undefined instead of string value

550 views Asked by At

I have this function "IsBrave" in my main.cpp.
If browser contains navigator.brave it calls the navigator.brave.isBrave() function with await.

But when call from browser's console the exported function, it prints undefined value instead of "Brave" on Brave browser. In other browsers result is "Unknown".

Tested in Brave Browser's Console

> var x = await navigator.brave.isBrave(); console.log(x);
true

>var y = Main.Module.IsBrave(); console.log(y);
undefined
It's Brave.

Desired output

> var x = await navigator.brave.isBrave(); console.log(x);
true

>var y = Main.Module.IsBrave(); console.log(y);
It's Brave.
true

I've printed something before the return val(u8"Brave"), no problem. But in browser's console get undefined value.

Any help is welcome. Thanks.


int main()
{
}

emscripten::val IsBrave()
{
    using namespace emscripten;
    bool isBrave = !!val::global()[u8"navigator"][u8"brave"] && !!(val::global()[u8"navigator"][u8"brave"].call<val>(u8"isBrave").await());
    if(isBrave)
    {
        std::cout<< "It's Brave." << std::endl; // PRINTED OK
        return val(u8"Brave"); // GET undefined in BROWSER
    }
    else
    {
        return val(u8"Unknown");
    }
}

EMSCRIPTEN_BINDINGS(exports)
{
    using namespace emscripten;
    function<val>(u8"IsBrave", &IsBrave);
}

Compiled with

em++.bat `
main.cpp `
-I ../CppInclude `
-I Include `
-o Module.js `
-std=c++17 `
--bind `
-s WASM=1 `
-s DISABLE_EXCEPTION_CATCHING=0 `
-s SINGLE_FILE=0 `
-s ASYNCIFY=1 `
-s VERBOSE=0 `
-O2 `
--profiling `
-s EXPORT_NAME=`'CreateModuleInstance`' `
-s MODULARIZE=1 `
-s EXPORTED_FUNCTIONS=[`'_main`'] `
-s EXTRA_EXPORTED_RUNTIME_METHODS=[`'ccall`',`'cwrap`',`'lengthBytesUTF8`',`'stringToUTF8`'] `
--pre-js "Js/Pre_Compiled.js" `
--post-js "Js/Post_Compiled.js" `
--extern-post-js "Js/ExternPost_Compiled.js" `
--extern-pre-js "Js/ExternPre_Compiled.js" `
1

There are 1 answers

0
Joma On BEST ANSWER

Solved with this example EmbindAsync