I have the following call to a Javascript promise:
deleteDatabase().then(function () {
doSomeStuff();
}, function (err) {
processError(err);
});
It works fine, but it looks really wordy. Is there a way to have a terser way to do this? Maybe something like this (which does not seem to work):
deleteDatabase().then(doSomeStuff(), processError(err));
You need to pass a function, not the result of calling them:
deleteDatabase().then(doSomeStuff, processError);
Of course, this will pass the result of the deleteDatabase() action to your doSomeStuff function, so if you expect it to get no arguments you will need to use the function expression as you did.
You have an issue with the syntax
deleteDatabase().then(doSomeStuff, processError);
if you put () after the function name it will call it immediately, by omitting the parenthesis you are passing a reference to the function and asking for it to be called at some point later on by the promise.
Related
I know that there's a completion handler for .set and .update, but I was wondering if there was something like that for .forEach.
For example, something like this:
firebase.database().ref().child('kid').orderByChild('date').on('value', function(snapshot) {
snapshot.forEach(function(kid) {
}, function(error) { //This is where the error is thrown
}
});
If this isn't possible, is there a workaround? I just need a function to call once the .forEach method is done running.
P.S. My function is actually stated in another file, but I just call it normally.
No, it is a synchronous javascript function. Simply add a line after the function.
I got the following code:
navigator.geolocation.getCurrentPosition(
successFunction
);
I was wondering why it is not required to use the '()' at the end of the succesFunction? Isn't it required to call a function with the '()' --> somefunction()
What's the logic behind it?
Because you're passing in the function reference, not the returned value of the function.
A function is a thing that can be invoked—where it runs code and returns a result. You invoke a function by using the parentheses. But, if you want to talk about the thing, if you want to pass the function around so that someone else can invoke it, you leave off the parentheses.
In this case, the getCurrentPosition() function is asking you to give it a function so that it can call it later on. So instead of invoking successFunction, you pass along a reference to it.
If you instead wrote:
navigator.geolocation.getCurrentPosition(
successFunction()
);
…then what would happen is successFunction() would be invoked—the code of the function would be run, and possibly return a value—and THEN you would invoke getCurrentPosition(), passing along as an argument whatever value successFunction returned.
In JavaScript you can pass functions as objects:
Try executing this example:
function myFunction() {
console.log('hello');
}
function anotherFunction(functionParameter) {
console.log('executing function passed as argument:');
functionParameter();
}
anotherFunction(myFunction);
This code will print:
"executing function passed as argument:"
"hello"
I don't understand why some JavaScript frameworks like ember.js use an anonymous function as a function parameter value. I would understand if the function was returning something, but it is not.
Here is a sample code of the routing system of ember.js that demonstrate my question:
App.Router.map(function() {
this.route("about", { path: "/about" });
this.route("favorites", { path: "/favs" });
});
Please explain me why this code creates an anonymous function as a parameter.
It's because that function .map is an async function, and that anonymous function is what to run AFTER .map completes.
Typically async functions look like:
function async(callback) {
//async stuff, yada
callback();
}
That callback is what you pass in to run once the async operations complete
So basically this creates a way to encapsulate functionality, and run the route set up w/e they need to. I'm not 100% familiar with amber, but my guess is that they do some setup and checking/validation before initializing the routes. Because you pass in the anonymous function, they can now defer the set up you specify until everything is set and ready to go!
A function passed in as a parameter means that the function will be run at some point during (or at the end of) the outer function. Often this is used to pass in a callback function.
For example, the map method might do some stuff and then call the anonymous function when finished:
function map(function) {
// Do some stuff
function();
}
I am using the following to pause the javascript for a few seconds:
setTimeout(start_countdown(),3000);
It does not work, the function is called regardless of the seconds. The following function does however work, which doesnt use a function.
setTimeout(alert('hi'),3000);
How can I solve this?
You need to pass a function reference. You are passing a function's return value.
The difference is this: one is a blueprint of the function you want to happen, the other means you are executing the function immediately and passing its return value to setTimeout.
setTimeout(start_countdown, 3000);
If you want to do something more complex than simply call a named function, OR you want to pass a param to the named function, you'll need to instead pass an anonymous function to the timeout and call your function within that:
setTimeout(function() {
start_countdown(/* possible params */);
/* other code here as required */
}, 3000);
If you dont need to pass params dont use ()
setTimeout(start_countdown,3000);
If you do you have to wrap your function
setTimeout(function(){start_countdown(parameter)},3000);
write instead
setTimeout(start_countdown, 3000);
without parens ()
the second example could be also written as
setTimeout(function() { alert('hi'); }, 3000);
In different browsers it works in different way. In IE you need to use the anonymous function to pass the parameters to the callback:
setTimeout(function(){alert('hi')},3000);
I know it's maybe an fairly easy basic knowledge for you, here I need to ask your help to see whether there is a 'hole' behind to improve. Please check the code below, can I set 'response' as callback parameter but not callSvc's? instead of this kinda 'tricky' way?
function callSvc(response, callback){
callback(response);
}
callSvc("I'm a response!",function(param_response){document.write(param_response);});
Thanks..
Update
Maybe this is good enough?
function callSvc(callback) {
callback("response");
}
callSvc(function(data) {
document.write(arguments[0]);
});
There shouldn't be anything tricky about closures in javascript. They are a language feature.
You can avoid the wrapping callSvc function as well, and jump straight into this:
var response = "I'm a response"
var callback = function(){document.write(response);};
The callback function can "see" response as if you passed it as a parameter, since it forms a closure.
callback(); //I'm a response
Eh? All that code looks to be the equivalent of
document.write("I'm a response!");
So you can bypass all the methods. You can also declare an anonymous function and call it immediately, if that's what you wanted to do:
(function(param_response){document.write(param_response);})("I'm a response!");
Or lastly, if you need to pass parameters to a callback that doesn't except any, then wrap it in an anonymous funciton
func_that_takes_callback(function(){the_real_callback(arg);});
Instead of defining your callback anonymously define it before hand:
function callSvc(response, callback){
callback(response);
}
function cb(param_response) {
document.write(param_response);
}
Then you can use it in a call to callSvc or on its own:
callSvc("I'm a response!", cb);
cb("I'm a response!");