I’m working with an async function that wraps an XMLHttpRequest in a Promise and I’m confused about how the await mechanism interacts with Promise resolution.
async function fetchAudioFile(itemId, category, shouldReturn=false){
let audioPromise = new Promise(function (resolve, reject){
var request = new XMLHttpRequest();
request.onload = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText !== "No Data"){
fileName = this.responseText;
if(shouldReturn == false){
sound = new Audio('media/files/audio/' + fileName);
sound.play();
}else{
resolve(fileName);
}
}else{
if(shouldReturn){
resolve('File Not Found');
}
}
}
};
request.open("GET", "api/fetch_audio.php?itemId=" + itemId + "&category=" + category, true);
request.send();
});
let response = await audioPromise;
if(shouldReturn){
return response;
}
}
Then I have another function that calls this async function:
function updateElement(itemId, category, element){
output = fetchAudioFile(itemId, category, true);
output.then(function(data){
if(data == "File Not Found"){
element.classList.remove('fa-play');
}
});
}
And finally I call it like this:
updateElement(itemId, category, buttons[i]);
I’m confused about how the await keyword works inside the async function. Does it return the resolved value to the calling function? What exactly does the resolve callback do in the Promise constructor? When I comment out the return statement after await, the Promise doesn’t get fulfilled. Can someone explain how these parts work together?