Question
Why my javascript function detected as not function on callback?
recently I try to jump into coding again after stopping for almost 7 years long. What I'm troubled now is a simple case where function became "not" function on callback.
Here is where it happens:
function xhrcall() {
let xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("POST", "/api", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("token=xxxxxxx");
xhr.onload = () => {
let x = xhr.status == 200 ? xhr.response : false; //console.log(x) gives proper response
return x;
}
}
When I try to declare it in variable or use it as callback it gives me Uncaught Error.
For example if I declare it like this
let fn = xhrcall()
console.log(fn) //will gives me undefined result
window.callback = xhrcall()
callback() //will gives uncaught error not a function
As I recalled, this should be fine and working yet it not.
This could be duplicate questions but I hope someone could explain what is actually wrong here. Did I miss the function scope? or is it the problem with return x?
Thank you.