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


#1

I found following example here: https://www.w3.org/TR/webmidi/#getting-access-to-the-midi-system

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.log(midi);

console shows “undefined”.

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

Btw:
Node.js 6.5.0
Chromium 53.0.2785.143
Electron 1.4.13.


#2

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.


#3

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