Skip to content

Instantly share code, notes, and snippets.

@noamross
Last active December 21, 2023 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamross/036846e8a664df6bf0444ba142caaef9 to your computer and use it in GitHub Desktop.
Save noamross/036846e8a664df6bf0444ba142caaef9 to your computer and use it in GitHub Desktop.
Experiments with WebR + XHR
# This function successfully runs the XHR request
# No response in the browser console because it is
# running in a web worker
webr::eval_js("
async function run() {
let response = await fetch('https://httpbin.org/json');
let data = await response.json();
return data;
}
run().then(data => console.log(data));
")
# I can create an item inside the R session
# The WebR worker is 'self' in this case
webr::eval_js("self.objs.globalEnv.bind('new_obj', 'hello there')")
new_obj # Success! Prints [1] "hello there"
# Is the function persistent?
webr::eval_js("run()") #Yes! another XHR request
# OK, so how can I get the data from the request into the session?
webr::eval_js("run().then(data => self.objs.globalEnv.bind('jsondata', JSON.stringify(data)))")
jsondata # Error:: object 'jsondata' not found. BUT the XHR request did happen.
# What about doing it inside the function?
webr::eval_js("
async function run() {
let response = await fetch('https://httpbin.org/json');
let data = await response.json();
self.objs.globalEnv.bind('jsondata', JSON.stringify(data))
}
run()
")
jsondata # still fails. Error: object 'jsondata' not found, XHR request still hapenning
# Drop the web call, just try in async. Is this about the async environment
webr::eval_js("
async function run() {
self.objs.globalEnv.bind('new_obj2', 'Hmmmm')
}
run()
")
new_obj2 # Binding succeeds, prints [1] 'Hmmmm'. Hmmm.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment