本文介绍了如何使用async/await进行反跳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入框.用户停止键入后,我想执行HTTP请求并等待结果.

I have an input box. After the user has stopped typing, I want to perform an HTTP request and await the results.

这是一个jsbin

由于jsbin上不允许网络请求,因此我改用setTimeout().

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);

但是,当我在框中键入内容时,正在执行搜索"会立即出现在每个字符上-我希望它仅在500ms过期后才显示.

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);

在指定时间参数后,您应该关闭debounce函数调用:

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>

这篇关于如何使用async/await进行反跳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:25