I have a (asynchronous) function that gets the ID of a logged in user in Chrome. I'm trying to return the value of the ID with a callback but it keeps returning 'undefined'.
Before someone tries to mark this a duplicate, I used the code from here (and tried other places too): How to return value from an asynchronous callback function? But it didn't work:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
callback(userInfo.id);
});
}
getGaia(function(id){
return id;
});
var gaiaId = getGaia();
I get the following error:
'callback' is a not a function
What exactly am I doing wrong / what is the correct code?
That is because you are not providing a callback.
function doSomethingLater(callback) {
setTimeout(callback, 1000);
}
console.log('This is before the callback');
doSomethingLater(function() {
console.log('This is the callback')
});
So when you are calling var gaiaId = getGaia(); you are not passing in a callback function
[Edit] This is what your code would need to look like:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
// This will call the function that you pass in below
//and pass in userInfo.if as a parameter
callback(userInfo.id);
});
}
var gaiaId = getGaia(function (id) {
// id === userInfo.id from above
// Do something with the id that you pass in
});
You can think of functions like variables in JavaScript,
So you can assign a function to a variable like this:
var foo = function () { ... }
This means that you can pass this into functions like normal variables. When you pass the function in as a parameter, you are assigning the function to the name that you specify in the parameters:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
All I have done above is, instead of creating the variable foo I just created the function inline:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
// Becomes:
function hasCallback(callback) {
callback(); // Using the function that you passed in
}
hasCallback(function () { ... });
Related
It's redundant but I am learning JS and I want to know how it really works.
Returning a function directly from a module
let func1 = function () {
let test = function () {
console.log("1");
}
return {
getTest : test
}
}
Returning a function by using a function
let func1 = function () {
let test = function () {
console.log("1");
}
return {
getTest : function () {
return test;
}
}
}
In the first case, the getTest property of your object points to a function, so calling it this way:
func1().getTest()
Should result in logging 1.
In the second case, getTest returns a function which returns another function, so you'd have to also call the result in order to get 1, this way:
func1().getTest()();
Calling just getTest will return your function object, rather than calling it.
Is it possible to pass a callback function that does not exist yet? My goal is to have a common function that will wait for another callback function to exist, when it does exist, it should execute it. This is what I have so far, but I can't figure out how to pass the function in that doesn't exist as a function yet.
function RunTemplateFunction(callback, userInfo) {
if ($.isFunction(callback)) {
callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(callback)) {
clearInterval(myInterval);
callback(userInfo);
}
}, 200);
}
}
I run the function like this:
RunTemplateFunction(MyFunctionToRun, GetUserInfo());
I get MyFunctionToRun is undefined for obvious reasons, I also tried the workaround of passing the function as a string and then convert the string to a function using eval(). But that throws the same error. I also thought of using the new function(), but that actually creates a new function.
Any help is appreciated. thank you.
If you call RunTemplateFunction by undefined there is no way we can see, is callback is defined or not, as we don't have reference to anything.
If you can modify the declaration to accept object as below, we can achieve what we want
function RunTemplateFunction(options, userInfo) {
if ($.isFunction(options.callback)) {
console.log('called1',userInfo);
options.callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(options.callback)) {
console.log('Called dynamically!!');
clearInterval(myInterval);
options.callback(userInfo);
}
}, 200);
}
}
var options = {}
RunTemplateFunction(options,{user:122});
options.callback = function(){
console.log("I'm called!!");
}
This will print
Called dynamically!!
I'm called!!
EDIT:
We can also call callback function in following way without setInterval, it will look different but options.callback variable is replaced by template.callMe function and its instantaneous also.
function TemplateRunner(userInfo){
this.callMe = function(cb){
this.templateFunction(cb);
}
this.templateFunction = function(callback){
callback(userInfo);
}
}
var template = new TemplateRunner({user:100})
template.callMe(function(user){
console.log('call me1',user);
});
template.callMe(function(user){
console.log('call me2',user);
})
This will print
call me1 {user: 100}
call me2 {user: 100}
I am studying JavaScript and I can't understand this.
function Out1()
{
function In1()
{
console.log("text inside function In1");
}
return In1();
}
function Out2()
{
return function In2()
{
console.log("text inside function In2");
};
}
Out1(); // text inside function In1
Out2(); //
Out2(); outputs nothing in console. What I am doing wrong?
Out2(); outputs nothing in console. What I am doing wrong?
Out2 returns a reference to the function it created. It doesn't call that function. You could call it by using () on the returned reference:
// vv-------- These call `Out2`
Out2()();
// ^^------ These call the function referenced returned by `Out2`
E.g.:
var f = Out2(); // `f` is now a reference to the `In2` function
f(); // This calls `In2`
I want to call a function that is in another function.
example for the functions:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
}
I need to call to funcTwo function, when I click on a button which is outside of these two functions
how can i do it?
No, You can't call unless you return that function.
Function2 is private to function1.
you use
function funcOne() {
return {
funcTwo :function() { // i want to call to this function
//do something
}
}
}
EDIT: Structuring code
function funcOne() {
var funcTwo = function() { // private function
//do something
}
return {
funcTwo : funcTwo
}
}
Now you can call it as:
funcOne().funcTwo()
As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:
var funcRef;
function funcOne() {
funcRef = function funcTwo() {
}
}
In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.
Reading some Douglas Crockford may help you understand...
Try recoding as:
function funcOne() {
this.funcTwo = function() {
}
}
I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.
It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.
You would have to define it outside the first function like so:
function funcOne() {
}
function funcTwo() { // i want to call to this function
//do something
}
Or you could also call the first function and return the second function like this:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
return functTwo;
}
And then call it like this:
var f = funcOne();
f();
Say I write this function...
var sayHi = function() {
return "hi";
}
alert(sayHi()); will return "hi".
Now if I write it this way...
var sayHi = function(callback) {
callback("hi");
}
How do I display "hi" with this function?
Based on an example here: http://nowjs.com/doc
You pass a function to sayHi, so I imagine this:
sayHi(alert);
you must have defined some callback function or pass a anonymous function:
var sayHi = function(callback) {
callback("hi");
}
sayHi(function(message){
alert(message);
});
Try this:
sayHi(function(msg){
alert(msg)
});
Your new sayHi function doesn't return a value, so you have to perform the alert in the callback function.
sayHi(function(value) {
alert(value);
});
sayHi(function(msg) {
alert(msg);
});
You have to invert your thinking process when using callbacks. Instead of writing the next operation first, you write the next operation last.
Here in example callback is a function. So you should pass function argument.
You may do this in 2 ways:
var some_fun = function(some_str) {
alert(some_str);
}
var sayHi = function(callback) {
callback("hi");
}
sayHi(some_fun)
or you can pass function when you call it:
var sayHi = function(callback) {
callback("hi");
}
sayHi(function(some_str){
alert(some_str);
});