I'm doing a website, in Vuejs, for a university project.
The scope of the function is to find out if a book is setted as favorite and, then, return the name of the icon so it will set automatically the right icon.
To do this I created the function setIcon():
setIcon: async function (id) {
var favs = await DataService.getFav();
var isFav = favs.find((book) => book.id === id);
if (isFav === undefined) {
return "favorite_border";
}
else
{
return "favorite";
}
}
The function, then, is simply called in the HTML part inside the icon tag.
For debugging reasons, I removed the icon tag and left the button one, so I can see what is the returned value from the function as the name of the Button.
<md-button class="md-button" @click.stop="setFav(book.id)">
{{ setIcon(book.id) }}
</md-button>
The problem is that the value the function return is a Promise Object and not the string "favorite_border" or "favorite".
So my question is how can I access the result of the promise in the HTML part?
I tried also to put the .then() part after setIcon() but the result is the same
You do not have to use async,try this:
setIcon: function(id) {
DataService.getFav().then((favs) = >{
var isFav = favs.find((book) = >book.id === id);
if (isFav === undefined) {
return "favorite_border";
} else {
return "favorite";
}
})
}
if DataService.getFav() method has no params and get the same result, you should cache the result in the other method, otherwise each execute setIcon will call DataService.getFav(),it's the waste of performance.