Skip to content

Is it legal to use Asyncify outside of a main loop? #13014

Open
@iliagrigorevdev

Description

@iliagrigorevdev

When I call a native C++ method with an asynchronous JS call outside of the main method, an incorrect result is returned (I expect HTTP status 200). Does anyone know what I'm doing wrong?

Chrome console output (without main function, with call from JS)

ASYNCIFY: handleSleep 0
ASYNCIFY: start unwind 5246952
ASYNCIFY: stop unwind
js_func: 0
ASYNCIFY: start rewind 5246952
ASYNCIFY: start: ƒ (){Asyncify.exportCallStack.push(x);try{return original.apply(null,arguments)}finally{if(ABORT)return;var y=Asyncify.exportCallStack.pop();assert(y===x);Asyncify.maybeStopUnwind()}}
ASYNCIFY: handleSleep 2
stop rewind

Chrome console output (with main function, without call from JS)

ASYNCIFY: handleSleep 0
ASYNCIFY: start unwind 5249000
ASYNCIFY: stop unwind
ASYNCIFY: start rewind 5249000
ASYNCIFY: start: ƒ (){Asyncify.exportCallStack.push(x);try{return original.apply(null,arguments)}finally{if(ABORT)return;var y=Asyncify.exportCallStack.pop();assert(y===x);Asyncify.maybeStopUnwind()}}
ASYNCIFY: handleSleep 2
ASYNCIFY: stop rewind
cpp_func: 200

func.cpp

#include <emscripten/val.h>
#include <emscripten/bind.h>
int func() {
  return emscripten::val::global().call<emscripten::val>("fetch", std::string("index.html")).await()["status"].as<int>();
}
//int main() {
//  printf("cpp_func: %d\n", func());
//  return 0;
//}
EMSCRIPTEN_BINDINGS(Func) {
  emscripten::function("func", &func);
}

index.html

<!doctype html>
<html>
  <script>
    var Module = {
      onRuntimeInitialized: function() {
        console.log("js_func: " + Module.func());
      }
    };
  </script>
  <script src="func.js"></script>
</html>

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(Func)
set(CMAKE_CXX_STANDARD 11)
add_library(Func STATIC
  func.cpp
)

compile.sh

emcmake cmake -B build
cd build
emmake make
emcc -O3 --bind -s ASYNCIFY -s ASYNCIFY_DEBUG -o ../func.js -Wl,--whole-archive libFunc.a
cd ..

serve.sh

python3 -m http.server

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions