javascript - 当第一个函数完成且为真时如何运行第二个函数
问题描述
我有 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>';
}
}
解决方案
- 尝试承诺
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)
}
});
推荐阅读
- html - 页面之间元素的 CSS 过渡是否可能?
- excel - 在VBA中更改字符串中的数字
- c# - 如何在二维数组中找到产品的收入
- typescript - 下一个图像的类型定义
- javascript - 有没有办法在不知道嵌套键的情况下传递访问器嵌套的 json。表抛出错误
- javascript - 取数组中最小值的对象
- google-app-engine - 登录后如何将用户连接到不同的 Cloud SQL 实例?
- ios - 将 IOS APP 上传到应用商店,无需分发配置文件
- javascript - 如何以特定方式将表单输入文本添加到 javascript 数组中?
- c++ - 为什么我的虚拟功能“独特”也不工作?