简体   繁体   English

如何使用async / await去抖?

[英]How can I debounce using async/await?

I have an input box. 我有一个输入框。 After the user has stopped typing, I want to perform an HTTP request and await the results. 用户停止输入后,我想执行HTTP请求并等待结果。

Here's a jsbin 这是一个jsbin

Since network requests aren't allowed on jsbin, I've used setTimeout() instead. 由于jsbin上不允许网络请求,我使用了setTimeout()

var log = console.log.bind(console)

var delayedResults = new Promise(function(resolve) {
  setTimeout(function(){
    resolve('Wooo I am the result!')
  }, 3000);
});

document.querySelector('input').addEventListener('input', _.debounce(async function(){
  log('Doing search')
  var result = await delayedResults
  log('Result is', result)
}), 500);

However when I type in the box, 'Doing search' appears immediately every character - I want it to only appear after the 500ms has expired. 但是,当我在框中输入时,“正在搜索”会立即显示每个字符 - 我希望它仅在500毫秒到期后出现。

How can I use debounce and await? 我如何使用去抖并等待?

The problem was at the last line: 问题出在最后一行:

}), 500);

You should close debounce function call after time argument was specified: 您应该在指定时间参数后关闭debounce函数调用:

}, 500));

 var log = console.log.bind(console); var delayedResults = new Promise( function(resolve) { setTimeout(function() { resolve('Wooo I am the result!'); }, 3000); } ); document.querySelector('input') .addEventListener('keydown', _.debounce(async function() { log('Doing search'); var result = await delayedResults; log('Result is', result); }, 500)); 
 <script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script> <input> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM