-
-
Save gtk2k/7fce6231af3fcdb159855b7b9435e4e9 to your computer and use it in GitHub Desktop.
Promise版とasync/awai版
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************* | |
* Promise版 | |
*******************************************/ | |
class MidiApi { | |
requestMIDI() { | |
return navigator.requestMIDIAccess().then(requestSuccess, requestError) | |
} | |
requestSuccess(midiAccess) { | |
this.inputs = midiAccess.inputs | |
this.outputs = midiAccess.outputs | |
return midiAccess // 呼び出し側でも使いたい場合はreturnで戻す | |
} | |
requestError(err) { | |
console.log(err) | |
} | |
} | |
export default new MidiApi() | |
//--------------------------------------------------- | |
// 呼び出し側 | |
import MidiApi from './MidiApi' | |
function callMidiApi() { | |
MidiApi.requestMIDI().then(midiAccess => { | |
// | |
}); | |
} | |
/******************************************* | |
* async/await版 | |
*******************************************/ | |
class MidiApi { | |
async function requestMIDI() { | |
try{ | |
// Promise版でのresloveで渡される値が戻り値として受け取れる | |
const midiAccess = await navigator.requestMIDIAccess() | |
requestSuccess(midiAccess) | |
return midiAccess // 呼び出し側でも使いたい場合はreturnでもどす | |
} catch (err) { // Promiseでのrejectで渡されるものがcatchの引数となる | |
requestError(err); | |
} | |
} | |
function success(midiAccess) { | |
this.inputs = midiAccess.inputs | |
this.outputs = midiAccess.outputs | |
} | |
funciton error(err) { | |
console.log(err) | |
} | |
} | |
export default new MidiApi(); | |
//--------------------------------------------------- | |
// 呼び出し側 | |
import MidiApi from './MidiApi' | |
async function callMidiApi() { | |
const midiAccess = await MidiApi.requestMIDI() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment