I have a class like this (simplified):
export class Foo {
constructor(el, menuItems ) {
this.id = this.el.dataset.id;
this.menuItems = menuItems;
this.fetchResult = async function (uri) {
fetch(uri, {
method: 'get'
})
.then(response => response.json())
.then(data => {
return data.saved === true;
})
.catch(function (err) {
console.log('Failed ', err);
return false;
});
}
}
doAction(action) {
const uri = 'foo/'+ action +'?id=' + this.id;
const map = {
'close': async () => {
const success = await this.fetchResult(action);
console.log(success); // says undefined?
}
/* some other actions */
}
return map[action];
}
attachDialogs() {
this.menuItems.addEventListener('click', (element) => {
this.doAction( element.dataset.action )();
});
}
}
For some reason the const success = await this.fetchResult(action);
does not wait for the result. It immediately proceeds, resulting in and 'undefined' value.
In the background the fetch is being done. How can I make it wait for the result?