strange reload require behavior, any explanations?

Hi there,

I have found that when using the npm package ‘peerjs’ I’m able to create some peer connection examples, but upon reloading the notebook nothing seems to work. Here’s my example of a notebook that appears to have failed to import the code correctly Peer js / Devin Bayly / Observable, but if I start a notebook from scratch and perform the same code cell by cell I’m all of a sudden able to use functions (Peer for instance) that in the previous notebook were ‘undefined’.

Any explanations for this behavior? Thanks so much!


Without viewing peer js, I sometimes get this when dependancies are loaded async. When you write them out one at a time the execute in a certain order, but when loaded via a refresh, they end up executing all at once in a random order. This can sometimes cause race conditions. Its important to test your notebooks behaviour after a refresh! I find tons of bugs that way. Add references to control the order of execution.

after viewing peerjs I see the main import is to peerjs, so basically the whole nobook doesn’t work becuase the constructor should be like:-

though not sure if thats your real problem but can you fix all the clear problems first.

oh interesting, I’ll give that a whirl really fast.

so something happens when I first write a notebook that puts Peer at a global scope, but upon refresh the race condition causes this not to happen? Either way I’ll just set Peer = peerjs.peerjs.Peer under the import cell. TY!!!

1 Like

Instead of implicitely relying on the object in the global scope, you can override it:

Peer = (await require("")).peerjs.Peer

Alternatively (if you want both peerjs and Peer as variables), I’d recommend a second cell that depends on the first:

peerjs = require("")).then(m => m.peerjs)
Peer = peerjs.Peer

In addition, you can have your connection cells return Promises that only return the connection instance on success:

conn2 = new Promise(resolve => p2.on('connection', resolve))

As an aside, I’ve made it a habit to prefix global objects (including less commonly used builtins) with window. to make the destinction more clear to the reader.

@mootari this is such a great set of recommendations, thanks so much!