How to return value from debounced function in javascript? [duplicate]

大兔子大兔子 提交于 2020-01-03 16:14:19

问题


I have a code like that:

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

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

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

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

(codepen link)

And the result in the console is:

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?


回答1:


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



回答2:


under the hood _.debounce uses setTimout, you need a callback to return value from a async function.

function originalFunction (callback) {
     callback("some value");
}

Here is a great link on the same, https://john-dugan.com/javascript-debounce/



来源:https://stackoverflow.com/questions/37836660/how-to-return-value-from-debounced-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!