3

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;
    },
  },
DerHelge
  • 53
  • 6
  • 1
    I think hits.forEach return is the problem just remove the return img and see if that does it. – mahatmanich Nov 25 '21 at 13:26
  • Hi, thanks for the quick answer! unfortunately this did not solve the problem. I can still log the img but i cant reach it to the outer function. Also I want to stop the forEach, when it finds an img, so i dont have to iterate ALL the items and get the last one. – DerHelge Nov 25 '21 at 13:46
  • Can you use different variable names for outer and inner 'img' to see if there is a problem – mahatmanich Nov 25 '21 at 13:53
  • I think this might be the issue: https://stackoverflow.com/questions/33154718/javascript-variable-scope-inside-foreach-loop – mahatmanich Nov 25 '21 at 14:07
  • Basically you have a variable conflict and overwrite the initial 'var img' you might wanna try using 'let img = " instead of var ... – mahatmanich Nov 25 '21 at 14:10
  • Doesn't the ".then"-function wait for the promise? there is no problem with the names of inner variables. I tested many alternatives, including calling another inner function. when i use This.imgURL there is a "not defined"-Error, if I use imgUrl whithout "this." it stays empty in outer function. – DerHelge Nov 25 '21 at 14:14
  • nope, this is not the problem. in outer function i use "imgURL", in Inner function i use "img". – DerHelge Nov 25 '21 at 14:22
  • https://jsfiddle.net/e7bn9Ls6/1/ should all work, but I guess it is a scope issue ... – mahatmanich Nov 25 '21 at 15:01
  • 1
    Ok, I found out that it is a async problem. I return imgUrl before the async function .search gives it a value. – DerHelge Nov 25 '21 at 15:46

0 Answers0