我是异步的新手,也许我只是不了解基本原理,但是我试图通过调用异步函数来等待onclick的用户输入,该函数会弹出一个模态并等待用户提交数据。在仅找到一两个甚至提到使用异步来等待对我的特定任务没有特别帮助的页面事件的来源之后,我想到了这一点:
asnyc func1 (){
var userInput = await async2();
//do stuff with user input
}
async func2(){
//build modal content specific to task
//display modal
return new Promise(function(resolve,reject){
$(document).on('click', '#save-input', function(e){
var input = $('#input-data').val();
resolve(input);
});
});
}
一切似乎都能正确调用,并且我得到了用户输入,但是func1从不会继续通过对async2的调用。因此,很明显,我错过了其中的一些关键方面,但我似乎无法从我的消息来源中提取它。
回调不是一种选择,这里的代码有很多,我无法简述,但以上所述是我需要执行的基准功能。
答案 0 :(得分:1)
这是我的工具:
// this is an async timeout util
const timeout = async ms => new Promise(res => setTimeout(res, ms));
let next = false; // this is to be changed on user input
async function waitUserInput() {
while (next === false) await timeout(50); // pause script but avoid browser to freeze ;)
next = false; // reset var
}
这是jQuery应用程序的示例:
async function myFunc() {
// do stuff
await waitUserInput();
$('#text').append('* user has clicked<br>')
await waitUserInput();
$('#text').append('* user has clicked second time')
// next bit
}
$('#user-input').click(() => next = true)
myFunc() // launch function and start waiting for user input
请参阅此有效的演示
// this is an async timeout util (very useful indeed)
const timeout = async ms => new Promise(res => setTimeout(res, ms));
let next = false; // this is to be changed on user input
async function waitUserInput() {
while (next === false) await timeout(50); // pause script but avoid browser to freeze ;)
next = false; // reset var
console.log('user input detected');
}
async function myFunc() {
// do stuff
await waitUserInput();
$('#text').append('* user has clicked<br>')
await waitUserInput();
$('#text').append('* user has clicked second time')
// next bit
}
$('#user-input').click(() => next = true)
myFunc()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='user-input' style='padding:15px;color:white; background: tomato; border: 0; border-radius:8px; font-weight: bold'>CLICK ME !</button>
<div id='text'>
</div>