如何从JavaScript中的反跳功能返回值

如何从JavaScript中的反跳功能返回值

本文介绍了如何从JavaScript中的反跳功能返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

var originalFunction = function() {
    return 'some value';
};

var debouncedFunction = _.debounce(originalFunction, 3000);

console.log('debouncedFunction() result: ', debouncedFunction());

console.log('originalFunction() result: ', originalFunction());

(codepen链接)

控制台中的结果是:

debouncedFunction() result:  undefined

originalFunction() result:  some value

如您所见,去反跳功能不会返回任何内容.我知道这是由去抖动功能中的内部计时器引起的,但是那周围还没有吗?

As you can see, the debounced function doesn't return anything. I understand that it's caused by an internal timer in the debounced function, but is there away around that?

推荐答案

这是因为去抖动的函数是异步调用的-尽管可以调用传递结果的另一个函数,但是您不能从它们返回值:

that's because debounced functions are called asynchronously - you can't return a value from them, although you can call another function passing the result:

var originalFunction = function() {
    console.log('some value');
    // or something like: callback(result)
};

var debouncedFunction = _.debounce(originalFunction, 3000);

console.log('debouncedFunction() result: ', debouncedFunction());

这篇关于如何从JavaScript中的反跳功能返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 11:32