Skip to content

Commit

Permalink
Fixed race condition with midi access promise
Browse files Browse the repository at this point in the history
  • Loading branch information
funwithtriangles committed Feb 4, 2020
1 parent 6f38115 commit e555257
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/inputs/MidiInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import getConnectedDevice from '../selectors/getConnectedDevice'

let store, midiAccess

const getMidiAccess = () => {
if (!midiAccess) midiAccess = navigator.requestMIDIAccess()
return midiAccess
}

const onMessage = (rawMessage) => {
const state = store.getState()
const deviceId = rawMessage.target.name
Expand Down Expand Up @@ -62,9 +67,11 @@ const onMessage = (rawMessage) => {
}
}

export const processDevices = () => {
export const processDevices = async () => {
const devices = {}

const midiAccess = await getMidiAccess()

midiAccess.inputs.forEach((entry) => {
devices[entry.name] = {
title: entry.name,
Expand All @@ -77,15 +84,13 @@ export const processDevices = () => {
store.dispatch(midiUpdateDevices(devices))
}

export default (injectedStore) => {
export default async (injectedStore) => {
store = injectedStore
const midiAccess = await getMidiAccess()

navigator.requestMIDIAccess().then((injectedMidiAccess) => {
midiAccess = injectedMidiAccess
processDevices()
processDevices()

midiAccess.onstatechange = () => {
processDevices()
}
})
midiAccess.onstatechange = () => {
processDevices()
}
}

0 comments on commit e555257

Please sign in to comment.