我试图做到这一点,以便连续响应的按钮单击在本机响应中异步发生。
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>
使用此代码,每秒多次单击按钮将导致“完成!”。被记录的次数远少于每秒
答案 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>