javascript - 使用异步函数等待来自 onclick 的用户输入

标签 javascript callback async-await event-handling dom-events

我是 async 的新手,可能只是没有深入了解基础知识,但我正在尝试通过调用弹出模式并等待用户提交数据的异步函数来等待来自 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。所以很明显,我遗漏了其中的一些关键方面,但我似乎无法从我的资源中提取它。

回调不是一个选项,这里的代码还有很多我无法简述的内容,但上面描述的是我需要执行的基本功能。

最佳答案

简单片段

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); // pauses script
    next = false; // reset var
}

使用 jQuery 的示例:

// just change the value of `next` for the script to continue
$('#user-input').click(() => next = true);

async function myFunc() {
    // do stuff before
    await waitUserInput(); // wait until user clicks
    // do stuff after
}

myFunc() // launch function and start waiting for user input

请看这个工作演示

// 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
let n = 1;

async function waitUserInput() {
    while (next === false) await timeout(50); // pause script but avoid browser to freeze ;)
    next = false; // reset var
}

async function myFunc() {
    $('#text').append(`* waiting user input...<br>`)
    await waitUserInput();
    $('#text').append(`* user has clicked ${n++} time(s)<br>`)
    myFunc()
}

$('#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>


进一步改进

这个示例可以很容易地改进以满足您的需求。例如,变量 next 也可用于存储用户输入值,而 waitUserInput 返回该值。这将导致编写如下内容:

const userResponse = await waitUserInput(); // get user input value

// 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 ;)
    const userInputVal = next;
    next = false; // reset var
    return userInputVal;
}

async function myFunc() {
    $('#text').append(`* waiting user input...<br>`)
    const userResponse = await waitUserInput();
    $('#text').append(`* user choice is ${userResponse}<br>`)
    myFunc()
}

$('#user-input').click(function() { next = $('#text-input').val() })

myFunc()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='text-input' type='text'/> 
<button id='user-input' style='padding:15px;color:white; background: tomato; border: 0; border-radius:8px; font-weight: bold'>SUBMIT !</button>
<div id='text'>
</div>

关于javascript - 使用异步函数等待来自 onclick 的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51374649/

相关文章:

javascript - Highcharts:在 IE 中将 Canvas 图像保存为本地文件

php - 获取可变大小的表单到 javascript 和 PHP (AJAX)

javascript - if else 条件在 jQuery 中不起作用

javascript - AJAX 之前的 Dojo 回调

c# - 如何让AsyncLocal流向 sibling ?

javascript - 如何在不重新加载整个应用程序的情况下获取异步数据

javascript - 可以在回调中设置 javascript 函数参数的值吗?

c# - 如何向 webform 项目添加回调

javascript - 我如何设置对变量的 promise 的响应

javascript - 在多个 settimeout 上使用 Async/Await