基于rusty_v8开发JS运行时:异步fetch操作处理方案求助
基于rusty_v8开发JS运行时的异步操作问题
背景
我正在基于v8(rusty_v8)开发一个简易JS运行时,处理异步操作时遇到了问题。
有一个从JS环境进入的入口函数:
fn message_from_worker( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _ret: v8::ReturnValue, ) // ...
该函数接收JS环境传来的不同类型消息并执行对应操作,其中一种消息是请求执行长耗时任务(fetch),我希望任务完成后能向JS环境返回消息。
当前核心实现
目前的fetch相关逻辑实现如下:
fn message_from_worker ... { // ... let message = args.get(0); let message = message.to_object(scope).unwrap(); let kind = utils::get(scope, message, "kind").to_rust_string_lossy(scope); match kind.as_str() { // ... "fetch" => { let request = utils::get(scope, message, "request"); let request = request.to_object(scope).unwrap(); let url = utils::get(scope, request, "url").to_rust_string_lossy(scope); let callback = utils::get(scope, message, "sendResponse"); let callback = match v8::Local::<v8::Function>::try_from(callback) { Ok(callback) => callback, Err(_) => { utils::throw_type_error(scope, "sendResponse is not a function"); return; } }; // 此处需执行异步HTTP请求 let response = { /* 目前为同步模拟响应 */ }; let undefined = v8::undefined(scope).into(); callback.call(scope, undefined, &[response.into()]); } // ...
遇到的错误
尝试使用阻塞式HTTP请求实现时:
reqwest::blocking::get(&url).unwrap()
触发报错:
Cannot drop a runtime in a context where blocking is not allowed. This happens when a runtime is dropped from within an asynchronous context.
疑问与思路
我考虑将所有待处理操作注册到全局状态,再从主线程轮询,但不确定具体实现方式,也不清楚是否能同时轮询多个操作,处理完成的任务后继续轮询剩余任务。
复现信息
源码已发布便于复现,当前代码位于fetch分支,执行以下命令可运行fetch脚本并触发fetch事件:
cargo run --bin cli scripts/fetch.js --event=fetch
内容的提问来源于stack exchange,提问作者max-lt
相关产品推荐
相关产品推荐

