Global variable with Web Midi Api is not visible out of scope?


I found following example here:

9.1 Getting Access to the MIDI System

This example shows how to request access to the MIDI system.
var midi = null;  // global MIDIAccess object

function onMIDISuccess( midiAccess ) {
      console.log( "MIDI ready!" );
      midi = midiAccess;  // store in the global (in real usage, would probably keep in an object instance)

function onMIDIFailure(msg) {
  console.log( "Failed to get MIDI access - " + msg );

navigator.requestMIDIAccess().then( onMIDISuccess, onMIDIFailure );

Appending this:

console shows “undefined”.

So, what do I have to learn? :nerd_face:

Node.js 6.5.0
Chromium 53.0.2785.143
Electron 1.4.13.


Your midi variable only gets filled with a value/object when the onMIDISuccess event was called.
The code seems to be promise based judging from the last line: navigator.requestMIDIAccess().then( onMIDISuccess, onMIDIFailure );.

To handle this type of asynchronous operations I would advice to learn how promises work in JavaScript.

You receive an undefined message because JavaScript doesn’t wait for the result. It just executes the console.log statement instantly, unless you use promises with proper then statements.


Aah ok, that makes sense. Now I know in which direction my studies should go.
Thanks alot. :+1: