⚠️ This IS MY FIRST ATTEMPT TO write IN English. Please note that the following code may be wrong. It is still being modified.
javascript using op to call rust is relatively simple, and the Deno source code also has many examples. This paper mainly focuses on how deno callsjavascript, or in another way, how to give deno data to javascript. The approach in this paper is to write polling functions in javascript that constantly ask rust for data. To achieve back pressure.
How to write
The pseudocode is as follows.
1 2 3 4 5 6 7 8 9 10 11 12
// Remember to register the OP function with the JS Runtime [op] op_rust_to_js_buffer() ->Result<Vec<u8>,AnyError> { // This DATA is a global static variable match DATA { Some(r)=> {Ok(r)}, Err(e) => {deno_core::error::custom_error{ "op_rust_to_js_buffer", "no Found data" }} } }
exportfunctionloopRustBuffer() { return { asyncnext() { let buffer = null; try { buffer = awaitDeno.core.opAsync("op_rust_to_js_buffer"); conststring = newTextDecoder().decode(newUint8Array(buffer)); console.log("rust send message to deno_js:", string); return { value: string, done: false, }; } catch (e) { return { value: buffer, done: true, }; } }, return() { /// Here you can manually control the asynchronous iterator to be "aborted" and released }, throw() { /// Here you can manually control the asynchronous iterator to be "aborted" and released }, }; }
async *waterOverflow() { do { const buffer = awaitloopRustBuffer().next(); /// Data-based specification to define when to end // if (isWaitingData > this.heightWaterMark) { // console.log( // "waterOverflow====>", // isWaitingData, // heightWaterMark // ); // break; // } if (!buffer.done) { this.isWaitingData++; } yield buffer; /// Here is the point, use do-while instead of finally, you can avoid stack overflow。 } while (true); }
(asyncfunction () { forawait (let num ofwaterOverflow()) { if (!num.done) { console.log("webView.waterOverflow:", num); } } })();