I have a problem to get data from variables inside an inner Javascript function to the outer function.
What I am trying to do is to search Algolia-hits from a special category to show the first hit that has an image. So I can use this image for an category-overview. All works fine, except that i dont manage to get the img-Url from the hits.
My function looks like:
methods: {
getCategoryPicture(categoryName) {
const index = this.searchClient.initIndex("Testindex");
var FacetFilterString = "Kategorie: " + categoryName;
var imgUrl = "";
// search for hits of category
index
.search("", {
facetFilters: [FacetFilterString],
attributesToRetrieve: ["img", "Marke"],
hitsPerPage: 50
})
.then(({ hits }) => {
// search for first hit with img
var img = ""
hits.forEach((element) => {
if (element["img"] != undefined)
{
img = "www.someurl.com/" + element["img"];
console.log(img);
return img
}
});
this.imgUrl = img
return img;
});
return imgUrl;
},
},
The function finds the url, I can log it, but I dont manage to get it from the inner ".then"-function to the outer function. I cant reach the variables of the outer-function. "this" doesnt work eather. (because it points to the module, not to the outer function, i guess?).
I just want to return the first img-url the function finds.
Edit: I updated the Code, so it might be more clear. The function "setImgUrl" logs the picture perfectly, but it does not update the outer variable "imgUrl".
methods: {
getCategoryPicture(categoryName) {
const index = this.searchClient.initIndex("Testindex");
var FacetFilterString = "Kategorie: " + categoryName;
var imgUrl = "";
index
.search("", {
facetFilters: [FacetFilterString],
attributesToRetrieve: ["img", "Marke"],
hitsPerPage: 50
})
.then(({ hits }) => {
var img = ""
hits.forEach((element) => {
if (element["img"] != undefined)
{
img = "www.someurl.com/" + element["img"];
setImgUrl(img);
}
});
return img
});
function setImgUrl(img) {
imgUrl = img;
console.log(img);
}
return imgUrl;
},
},