使连续的按钮单击异步

时间:2019-04-25 20:22:38

标签: javascript react-native

我试图做到这一点,以便连续响应的按钮单击在本机响应中异步发生。

  onclick = async () => {
    await this.f();
  }

  async f() {
    let promise = new Promise((resolve, reject) => {
      setTimeout(() => resolve("done!"), 1000)
    });
    let result = await promise; 
    console.log(result); // "done!"
  }

 <TouchableOpacity
   onPress={() => this.onclick ()}
   style={styles.headerButton}
   >
     <Text style={styles.headerButtonButtonText}>Edit</Text>
 </TouchableOpacity>

使用此代码,每秒多次单击按钮将导致“完成!”。被记录的次数远少于每秒

1 个答案:

答案 0 :(得分:0)

在此代码段中效果很好。我认为您的问题是您await this.f()onclick函数上,但是this.f()实际上没有返回承诺。

let f = async () => {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });
  let result = await promise; 
  console.log(result); // "done!"
}
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser-polyfill.min.js"></script>
  </head>
  <body>
    <button onclick="f()">click me</button>
  </body>
</html>