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

问题描述 投票:1回答:1

我是async的新手,也许只是我没有围绕基础,但我试图通过调用弹出模式的异步函数等待用户输入来等待用户提交数据。在找到一个或两个源甚至提到使用异步等待页面事件对我的特定任务没有特别帮助...我想出了这个:

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。所以显然我错过了一些关键的方面,但我似乎无法从我的来源中提取它。

回调不是一个选项,这里的代码还有很多,但我可以简单介绍一下,但上面描述的是我需要执行的基线功能。

javascript javascript-events callback async-await event-handling
1个回答
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

请参阅这个有效的DEMO

// 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>
© www.soinside.com 2019 - 2024. All rights reserved.