【问题标题】:Wait for click event inside a for loop - similar to prompt()在 for 循环中等待点击事件 - 类似于 prompt()
【发布时间】:2019-02-28 00:49:28
【问题描述】:

这可能不是最好的标题。我正在尝试理解回调函数,我想知道如何在不丢失 for 循环的情况下替换以下代码中的 prompt()?

for(i=0;i<4;i++){
  let x = prompt("Input an integer");
  // store input into an array
}

我尝试过类似的方法:

for(let i = 0; i<4; i++){
  let x = document.getElementById("someId");
  x.addEventListener("click", rcvInput(function(i){
    if(i == 3){
      x.removeEventListener("click", rcvInput)
    }
  }));
}
function rcvInput(callback){
  //store input into an array
  callback();
}

我知道这可以在没有 for 循环的情况下完成,我更好奇回调是否能够暂停循环并等待输入?

【问题讨论】:

  • 我不太清楚你想做什么,但我强烈怀疑你真的想多了。退后一步,这里的目标是什么?当用户单击按钮时,您似乎只是想从输入中获取值。那么循环或回调或其中任何一个的目的是什么?

标签: javascript for-loop prompt


【解决方案1】:

根据您的最终目标,我很确定有更好的方法来实现。但是为了这样做:

您可以创建一个方法,该方法返回一个在点击发生时解析的承诺。然后你可以使用async/await 来做你需要的事情。

通过在其上使用Promiseawaiting,您可以在技术上“暂停”您的for 循环,直到发生某些事情。在这种情况下,点击一下。

记住包含for 循环的方法必须是async

function getClick() {
  return new Promise(acc => {
    function handleClick() {
      document.removeEventListener('click', handleClick);
      acc();
    }
    document.addEventListener('click', handleClick);
  });
}


async function main() {
  for (let i=0;i<4;i++) {
    console.log("waiting for a click", i);
    await getClick();
    console.log("click received", i);
  }
  console.log("done");
}

main();

plunkr 中尝试一下。

【讨论】:

  • 感谢 Amir - 只是为了理解... async 方法暂停 for 循环,并等待 getClick() 返回 void?
  • getClick 返回一个承诺。 await 等待该承诺解决。在此示例中,promise 解析为 void,但从技术上讲,您可以将其解析为您想要的任何内容,例如 acc('the thing you want')。然后,您将通过await 获得该解析值。 const resolvedValue = await getClick().
【解决方案2】:

要实现:

for(var i=0;i<4;i++){
  let x = prompt("Input an integer"); // WAIT FOR PROMPT
  // ...
  // LOOP CODE AFTER PROMPT
}

你可以使用递归:

function promptLoop(count){
    let x =  prompt("Input an integer");
    // ...
    // LOOP CODE AFTER PROMPT
    if (count > 0) promptLoop(count - 1)
}

并像这样使用它:

promptLoop(4);

您的第二种情况不同,可以这样调整:

function loop(count, method) {
    if (count > 0) method(() => loop(count - 1, method), count);
}

然后您的函数将接受下一个回调,如下所示:

function toBeLooped(next){
    // do stuff
    next() // continues loop 
}

loop(3, toBeLooped);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2022-11-30
    • 2023-01-20
    • 2018-06-09
    • 2018-01-06
    相关资源
    最近更新 更多