当我点击一个按钮时,我该如何做到这一点,它会解决一个承诺,如果我再次点击它会等到之前的承诺得到解决

How can i make so when i click a button it will resolve a promise, and if i click again it will wait untill the previous promise is resolved

  let msg = "Done";
  function promise() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("Done");
      }, 2000);
    });
  }
  async function func1() {
    msg = "Pending";
    console.log("Starting...");
    const a = await promise();
    console.log(a);
    msg = a;
  }

  async function func2() {
    console.log("Queued");
  }

  async function call() {
    if ((msg) === "Done") {
      func1();
    } else {
      func2();
    }
  }
<h1>PROMISE</h1>
<input onclick="call()" type="button" value="Click me " />

我把这段代码加入到func2()中,它在前面的promise resolve后运行func1(),但它也是在点击后立即运行。我该怎么做,它只会在之前的承诺得到解决后运行。

func2() {
  console.log("Queued");
  await func1();
  func1();
}

编辑: 伙计们!我使用 Date().getTime() 方法解决了这个问题,并添加了“clicks”变量。结果几乎相同。但是做的方式是不同的。当我单击它时,它会立即开始执行承诺,但我希望它等到上一次单击的承诺完成,然后才开始执行新的承诺。我认为必须有一些其他更简单的解决方案。

 let msg = "Done";
  let clicks = 0;
  let t1;
  let t2;
  let timeout = 0;
  let txt = "";
  function promise() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("Done");
      }, 2000 * clicks - timeout);
    });
  }
  async function func1() {
    clicks = 1;
    timeout = 0;
    txt = "";
    msg = "Pending";

    let time = new Date();
    t1 = time.getTime();
    const a = await promise();
    let taym = new Date();
    let now = taym.getTime();
    createDiv(now, t1, txt);
    msg = a;
  }

  async function func2() {
    clicks++;
    let time = new Date();
    t2 = time.getTime();
    timeout = t2 - t1;
    const a = await promise();
    let taym = new Date();
    let now = taym.getTime();
    txt = " and " + (now - t2) + " ms after last click";
    createDiv(now, t1, txt);
  }

  async function call() {
    if (msg === "Done") {
      func1();
    } else {
      func2();
    }
  }

  function createDiv(a, b, c) {
    let div = document.createElement("div");
    div.innerHTML = "Created " + (a - b) + " ms after main click" + c;
    document.body.appendChild(div);
  }
<h1>PROMISE</h1>
<input onclick="call()" type="button" value="Click me " />

   

下面的代码可以满足您的需求

解析到事件,只是为了表明第二次点击显示的时间戳是第一次点击时间戳,因为这就是本例中的承诺解析到的内容

虽然不确定这段代码有多有用

const promise = new Promise(resolve => {
  document.getElementById('bang').addEventListener('click', e => {
    console.log('first click');
    resolve(e);
  }, { once: true });
})
promise.then(e => {
  console.log(e.timeStamp, e.type, e.target.id);
  document.getElementById('bang').addEventListener('click', e => {
    promise.then(e => {
      console.log('not the first click');
      console.log(e.timeStamp, e.type, e.target.id);
    })
  })
})
<button id="bang">Resolve the promise</button>