Skip to content

Instantly share code, notes, and snippets.

@gtk2k
Forked from anonymous/promisetoasyncawait.js
Last active December 31, 2017 09:12
Show Gist options
  • Save gtk2k/7fce6231af3fcdb159855b7b9435e4e9 to your computer and use it in GitHub Desktop.
Save gtk2k/7fce6231af3fcdb159855b7b9435e4e9 to your computer and use it in GitHub Desktop.
Promise版とasync/awai版
/*******************************************
* 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