简体   繁体   中英

How running JavaScript function in order?

What am I doing?
I'm try running two function in order but JavaScript is calling and running two function in same time.

What's the problem?
The setModalBox function give undefined error if is called before setProjects function.

What have I already tried?
I tried used Promise with setTimeout it work, but can sometimes setModalBox function be called before and give of same error.

Part of JavaScript:

  init() {
    this.setProjects();
    // this.setModalBox();
  }

  setProjects() {
    let response_promise = fetch("contents/projects.json")

    document.addEventListener("DOMContentLoaded", function() {
      response_promise.then(response => response.json().then(projects => {
        // ? Gradient in border for each color language

        for(let project in projects){
          // Div project
          var div = document.createElement("div");
          div.className = "project";
          div.id = `project-${projects[project].name}`
          document.querySelector(".projects").appendChild(div);

          // Tittle project
          var h1 = document.createElement("h1");
          h1.className = "tittle-project";
          h1.innerHTML = projects[project].name;
          document.querySelector(`#project-${projects[project].name}`).appendChild(h1);

          // Paragraph project
          var p = document.createElement("p");
          p.className = "about-project";
          p.innerHTML = projects[project].about;
          document.querySelector(`#project-${projects[project].name}`).appendChild(p);
        }
      }))
    }, false)

    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        this.setModalBox()
      }, Math.random() * 2000)
    })
  };

  setModalBox(){
    let projectsLength = document.querySelectorAll(".projects")[0].children.length;
    let modalBox = this.modalBox;

    for(let i = 0; i <= projectsLength; i++){
      let projectsAll = document.querySelectorAll(".projects")[0].children[i];

      // That "try" is for not to show error in console
      try{
        // Open Modal Box
        projectsAll.onclick = function(){
          modalBox.style.display = "block"
        };
      }catch{}

      // Close Modal Box, when click at "X"
      this.modalBoxClose.onclick = function(){
        modalBox.style.display = "None"
      };

      // Close Modal Box, when click out of Modal Box
      window.onclick = function(){
        if(event.target == modalBox){
          modalBox.style.display = "None"
        }
      }

      // Close Modal Box, when press esc key
      document.addEventListener("keydown", function(event){
        if(event.key == "Escape"){
          modalBox.style.display = "None"
        }
      })
    }
  }

HTML:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Projetos - Vitor Hugo's Portifolio</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>

  <body>
    <header>
      <div id="wrapperJS" style="position: relative; overflow: hidden">
      <nav>
        <a class="logo" href="/">Vitor Hugo</a>
        <div class="mobile-menu">
          <div class="line-1"></div>
          <div class="line-2"></div>
          <div class="line-3"></div>
        </div>
          <ul class="nav-list">
            <li><a href="index.html">Home</a></li>
            <li><a href="sobre.html">Sobre</a></li>
            <li><a href="projetos.html">Projetos</a></li>
            <li><a href="contatos.html">Contato</a></li>
          </ul>
        </nav>
      </div>
    </header>
    <script src="mobile-screen.js"></script>

    <!-- Boxes -->
    <div class="projects"></div>

    <!-- Modal Boxes -->
    <div class="modal-box">
      <div class="modal-box-contents">
        <span class="modal-box-close">&times;</span>
        <p>test</p>
      </div>
    </div>
  </body>
</html>

What I have to do? please help me. If need more information,ask. And sorry for any error orthography and grammar I am studing English.

Try async/await. For example you can do it like this:

const setProjects = async () => {
try {
await // Put your code here
}catch (err){
console.log(err)
}
};

Then:

setProjects().then(setModalBox());

Now your functions will be executed in an order.

You can just call setModalBox at the end of the DOMContentLoaded event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM