Is there a way to fake a synchronous XHR request?

谁说我不能喝 提交于 2019-12-08 17:22:48

问题


I'm porting a pile of C++ code to Javascript using the Emscripten system. The C++ code has many calls to fopen which is a synchronous IO call. Within Emscripten, we simulate this using an XHR request to a local resource however, within Firefox synchronous XHR calls (with a responseType of blob or arraybuffer) are only supported within a Web-Worker. Converting all that c++ code to adapt to asynchronous IO code seems very complicated so for my first try, I'd like to see if I can fake a synchronous XHR request.

My initial thought was that the main loop could share some state with a web-worker which could make the synchronous io call and update the shared state while the main loop paused and waited for the web-worker finished. DISCLAIMER: I know this is not the typical Javascript way but I am porting synchronous code, not writing new code from scratch (in which I would definitely have used asynchronous IO).

Given the restrictions on sharing state between a web-worker and the main-loop, this idea looks untenable.

Are there other ways to do this?


回答1:


So after seeing all the answers and doing some of my own reading, it appears the best answer is: "You can, but only for text data and you have to convert it back to binary data". This is slow, but does work.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest%2FSending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers




回答2:


Have you looked at testing libraries like qunit and sinon? I think Jasmine may also be able to do it, but I know that sinon can do this

http://sinonjs.org/docs/#server



来源:https://stackoverflow.com/questions/16281511/is-there-a-way-to-fake-a-synchronous-xhr-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!