Key
Add the async keyword to the anonymous arrow inline function.
Example
class MyClass{
...
initButton() {
let button = document.createElement('button');
button.innerHTML = 'LongRun';
this.button.addEventListener('Play', async () => {
this.buffer = await this.loadAudioBuffer(url); // <-- wait task finished
this.playSound(this.buffer);
});
}
loadAudioBuffer(url){
return new Promise(resolve => {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = () => {
this.context.decodeAudioData(request.response, (theBuffer) => {
console.log('Get the data.')
this.buffer = theBuffer;
// this.playSound(this.buffer)
resolve(this.buffer);
console.log('buffer = ', this.buffer);
}, function () {
console.log('[Error] loadAudioBuffer:: decodeAudioData error.')
});
}
request.send();});
}