emscripten-core / emscripten-core/emscripten
Is it legal to use Asyncify outside of a main loop?
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
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
```cpp
#include
#include
int func() {
return emscripten::val::global().call("fetch", std::string("index.html")).await()["status"].as();
}
//int main() {
// printf("cpp_func: %d\n", func());
// return 0;
//}
EMSCRIPTEN_BINDINGS(Func) {
emscripten::function("func", &func);
}
```
## index.html
```html
var Module = {
onRuntimeInitialized: function() {
console.log("js_func: " + Module.func());
}
};
```
## CMakeLists.txt
```cmake
cmake_minimum_required(VERSION 3.10)
project(Func)
set(CMAKE_CXX_STANDARD 11)
add_library(Func STATIC
func.cpp
)
```
## compile.sh
```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
```sh
python3 -m http.server
```
Contributor guide
Assessment
This issue has not been assessed yet.