首页 > 解决方案 > 当第一个函数完成且为真时如何运行第二个函数

问题描述

我有 2 个简单的功能,第一个是检查代码是否正确。然后我有第二个发生了一些事情的地方。只有当用户输入正确的代码时,我才想运行第二个函数。我尝试使用 Settimeout,但过了一会儿,第二个函数运行但没有通过第一个函数的测试。

谢谢你的帮助

两者都在全局范围内

//Check The code To start the conversations
function CheckCode(msg) {
    const num = msg;
    
    //Check if The code is Valid 
    if(num == 333 ) {
        MessageEl.innerHTML = `<div>${msg} Code is Right, How are you Today!</div>`;
        return;
    }

     else {
        MessageEl.innerHTML = `<div>${msg} Code is Wrong, Please Speak The Right Code To talk to me</div>`;
        return;
     }

}


function TalkTheTalk(msg) {

    const talk = msg; 

    const greetings = ["I'm good", "I'm fine", "I'm Ok"];

     const result = greetings.find((greeting)=> {
         return greeting === talk;
        });

        if(result) {
            MessageEl.innerHTML = '<div> Im so happy to hear that! What can i do for you today ! </div>';
        }
        else {
            MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
            
        }    
    
}

标签: javascripthtmlcss

解决方案


  • 尝试承诺
var pro = function () { 
  return new Promise((resolve, reject) => { 
      function CheckCode(msg) {
         const num = msg;
       if(num == 333 ) {
        MessageEl.innerHTML = `<div>${msg} Code is Right, How are you Today!</div>`;
        resolve(num)
        return;
      }
     else {
        MessageEl.innerHTML = `<div>${msg} Code is Wrong, Please Speak The Right Code To talk to me</div>`;
        return;
       }
     }
   })
}
pro().then(check_data => { 
  if(typeof check_data == "number") { 
     TalkTheTalk(check_data)
  }
});

推荐阅读