Can't Edit Global Variable Inside Function

David Source

I'm declaring the global variable str, then editing it inside a function, and trying to call it within that function. However, when called, it returns the initial global value of ''.

var str = '';
function getProjects(service) {
  //find all projects

    fetch(`http://localhost:8888/wp-json/wp/v2/projects?_embed`)
      // get the response as JSON
      .then(r => r.json())
      // go through the posts and append each posts' title to the HTML element
      .then(projects => {
        //for each project, find categories
        projects.forEach(project => {
          // find categories of each project
          project.categories.forEach(category => {
            // check if category name is equal to a service name
            fetch(`http://localhost:8888/wp-json/wp/v2/categories/${category}`)
              .then(r => r.json())
              .then(response => {
                if(serviceData[service].slug == response.slug) {
                  // if previous evaluates to true, add project to service
                  if(project._embedded['wp:featuredmedia']) {
                    str += `<div class='project-div'><a href='#'><img src='${project._embedded['wp:featuredmedia'][0].media_details.sizes.medium.source_url}' /><div class='bottom-text'>${project.title.rendered}</div></a></div>`;
                  }
                }
              })
          })
        })

      })
      .then(() => {
        document.getElementById('projects-container').innerHTML = str;
      })
}

javascript

Answers

answered 3 months ago Alex #1

You should use a regular for loop rather than a forEach. Higher order functions native to array prototypes are not compatible with promisified functions. Try changing it to a for loop and see if that fixes your problem.

Also, to demonstrate how a forEach breaks your code, console log right after you append to the string and then console log right before you use that edited string. More than likely you will see the latter console log happening before the ones in the forEach.

answered 3 months ago Jyasveer Gotta #2

In the 2rd then() handler return the str and accept it as a parameter in the 3rd then() handler like this below

              if(project._embedded['wp:featuredmedia']) {
                //...
                return str;
              }
            }
          })
      })
    })

  })
  .then((str) => {
    document.getElementById('projects-container').innerHTML = str;
  })

comments powered by Disqus