Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to fake a synchronous XHR request?

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?

like image 807
Michael Bishop Avatar asked Apr 29 '13 14:04

Michael Bishop


2 Answers

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

like image 125
Michael Bishop Avatar answered Nov 15 '22 14:11

Michael Bishop


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

like image 31
ChrisIPowell Avatar answered Nov 15 '22 16:11

ChrisIPowell