Async issue in Web Csound/p5.js

Hi all,

Things are moving along with learning Web Csound and p5.js, but I’m still figuring out how to work with async functions and race conditions in this environment (i.e. I’m new to the web development world). Here’s the latest iteration of my project. I’ve added a waveform visualization that uses .decodeAudioData() in a function called generate_peaks() on line 55 of setupCsound.js.

In order to get the waveform to be drawn, I had to add this test condition on line 18 of the draw() function in sketch.js: if (sample_list[0]) {. When you comment out the test condition (lines 18 and 26), the waveform doesn’t get drawn and an error message says that sample_list[0] is undefined. Is that because there’s a race condition where generate_peaks() hasn’t yet finished generating the sample_list before the draw function is called in sketch.js? sample_list[0] does eventually get defined because you can explore it in the JavaScript console.

While I have a workaround in line 18 of sketch.js, I wonder if there’s a better solution that defers execution of the draw() function until generate_peaks() has finished generating the sample_list. That seems like a basic async function solution, but I can’t figure out how to implement it. Any suggestions?

Thanks for your patience and guidance as I trudge through the async world!

Jason

@JasonHallen I looked at the project and it seems to be working. Is everything sorted out now or is there something that is still off?

Thanks for checking in, Steven. The project is working because I added a test condition to see if sample_list[0] has been generated before the draw() function tries to use the data in the array. Without that test condition, part of the code breaks. In other words, the program needs to do some pre-processing before some of the data can be visualized.

I guess I’m getting a sense for how to build a GUI that sometimes needs to process data asyncronously. My strategy (and the strategy I’ve seen in some of the Csound/p5.js examples ) is to add if (condition) tests to make sure p5.js doesn’t try to do something before the condition is true (i.e. the data has been processed and is ready). And then while waiting for the condition to become true I can put in some kind of “Loading…” animation.

Does that seem like a reasonable approach, especially in this domain of Web Csound and js programming?

Thanks!
Jason

Yeah, I think you got the gist of it. Just need to trace through all the pieces that need to load first and have other parts wait until that’s all prepped. :+1: