Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Here's a jsbin

Since network requests aren't allowed on jsbin, I've used setTimeout() instead.

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.

How can I use debounce and await?

like image 307
mikemaccana Avatar asked Jun 12 '17 14:06

mikemaccana


People also ask

What is async Debounce?

A debounced function that delays invoking asynchronous functions.

Does await block execution?

Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the await expression.

What is async await used for?

Use of async and await enables the use of ordinary try / catch blocks around asynchronous code. Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError .


1 Answers

The problem was at the last line:

}), 500);

You should close debounce function call after time argument was specified:

}, 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>
like image 69
G07cha Avatar answered Sep 19 '22 10:09

G07cha