html - 将异步 onSuccess 转换为 Promise 并等待
问题描述
我有带有输入的 html 页面
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<?!= include("index-css"); ?>
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div>
<button id="del" type="button"><RESET</button>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Логин:" autofocus >
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Номер стола:" >
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Заказ:" >
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
<?!= include("index-js"); ?>
</body>
</html>f
在 include(index-js.html) 我写了这个
<script>
var curInpID;
var findData;
function keyPressFunction(ev) {
var inputData = ev.target.value;
if (ev.code !== 'Enter') return;
curInpID = ev.target.id;
google.script.run.withSuccessHandler(onSuccess).searchData(inputData);
console.log(findData); //result onSuccess here
for (const i of formControl) {
if (i.value === '') {
i.nextElementSibling.focus();
break;
}
}
}
function onSuccess(_findData) {
findData = _findData;
}
</script>
onSuccess 转到应用程序脚本,检查那里的输入值并在 findData 中返回真/假
function searchData(data){
for (let i = 0; i < arrLogins.length; i++){
if(arrLogins[i].indexOf(login)!==-1){
firstValid = true;
return firstValid;
}
}
firstValid = false;
return firstValid;
}
由于 onSuccess 是异步的,这种方式运行缓慢,有时会返回错误的值给 findData。在上一个主题中,一位同事建议我将其转换为 Promise 并等待。
我在这个网站上找到了一些异步、等待和承诺的例子,但我不明白,我需要在这里转换什么。请帮我!谢谢!
解决方案
推荐阅读
- java - !strcmp(locale, "C"):Error:Assert failed:in file baseapi.cpp, line 209
- reactjs - 如何使用 mobx 观察可观察数组上的 object.property 变化
- kotlin - 如何在 WebUI 中渲染 StreamObserver (ktor + freemarker)
- node.js - 如何从我的服务器中忽略或删除 dns 缓存浏览器?
- python - Python gui 应用工具?
- c# - Specflow 覆盖原始异常堆栈跟踪
- kotlin - 重写方法的 open 修饰符背后的推理
- android - 将商品添加到购物车列表
- unity3d - 在 3D Arcore 中转换场景中的 2D 对象
- airflow - 添加第一个 dag 时出现 Cloud Composer 调度程序错误