Check for completion on the firebase js .forEach method? - javascript

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.

Related

Javascript asynchronous assignment and callback

I'm sure there's an easy way to do this, but I'm having difficulty wrapping my mind around asynchronous calls and their flows. I'm trying to do a simple assignment statement in javascript, followed by setting a timer to perform operations on that object once it's been assigned. I have something along the lines of:
var info = getInfo();
$timeout(updateInfo(info), 5000);
However, I don't want the timeout to be executed until info is set initially. I've tried looking into using .then or some form of callback, but I haven't successfully determined how to do that. I'm unsure if having the parameter of info in the updateInfo call makes it so that I can't use callbacks in getInfo or what the correct flow is. I've read other articles and stack overflow responses, but couldn't find one dealing with asynchronous assignment and then using that as a paremter in a subsequent call.
getInfo and updateInfo are methods that return Highcharts graph config objects. Without copying over all the specific details:
getInfo: function() {
return {
options: {
chart: {
type: 'line'
}
}
...
}
}
updateInfo: function(info) {
// Here computations are performed on plot series data.
info.series.push(...)
}
Both getInfo and updateInfo looks pretty sync to me.
So there shouldn't be any synchronization problem.
The only thing I noticed is the wrong use of $timeout in your example.
$timeout(updateInfo(info), 5000); this way updateInfo will be called before the timeout starts and the returned value will be passed as a parameter.
In order to call updateInfo after 5 seconds you have to use anonymous function or bind function.
$timeout(function() { updateInfo(info); }, 5000);
$timeout(updateInfo.bind(null, info), 5000);
For more info about bind.
You should remember that although JavaScript does some asynchronous actions, yet the assignment to a variable is synchronous, which means that it occurs at the moment you requested for it, and won't go on to the next line until it's done.
If getInfo itself has the variable info in scope and updates it during the asynchronous call, then you shouldn't assign a value to it in the invocation of the function.
If I confused you, let me guess what you do there (and please provide the getInfo function for clarifying your question).
I'm pretty sure what getInfo does is an ajax call. So if you already use jQuery, you can simply use their ajax function:
function getInfo(){
$.ajax({
url: "/api/items"
}).done(updateInfo);
}
function updateInfo(data){
console.log ('Do something with', data);
}
getInfo();
See full documentation:
http://api.jquery.com/jquery.ajax/

What is difference between calling a function and callback function?

What is the difference between following snippets
// calling a function
function execute(){
}
function fn(){
asynchronousFunction(function(){
execute();
})
}
fn();
How the below snippet is different from above
// callback a function
function execute(){
}
function fn(done){
asynchronousFunction(function(){
done();
})
}
fn(execute);
In which way callback is different from calling a function directly? What are pros and cons of each approach?
If you call a function, it will execute immediately.
If you pass the function as an argument to another function, then some other code will call it later (at which point it will execute).
They aren't different approaches for doing the same thing. You use a callback when you are writing a function that needs to do something at some point, but when what that something is depends on something outside the function.
The classic example is addEventListener. For the sake of discussion, let's limit ourselves to click events. You have a standard function for making something happen when something is clicked. Lots of programs want something to happen when something is clicked, but that something can be almost anything.
In first case, your function fn() can see execute() and the parameter is optional, because anytime you call fn() will be called execute().
in second case, you made your function more "general" and you may customize your callback function
The first option presents fn as a simple function that starts some kind of asynchronous action and doesn't present any other information to the outside. If fn is something like uploadData, then you'd have a simple function that tries to upload it (and maybe display an error message if it fails, or a success message when it's done), but the caller can only start it and do nothing else.
The second option additionally allows the caller of fn to decide what should happen when fn completes. So if fn is uploadData, then the caller is able to also specify what should happen once the data has been uploaded (or if there has been an error).
Callbacks like these gives you a lot of flexibility. In your second example, you are able to say: "Do fn(), and do the asynchronous function, and if you have finished, then call done()." And the point is, you can decide what done() does, although you have no insight in the method that calls it.
Delivering functions as an argument, that are to be executed e.g. at the begin, at the end or at other events, is a fundamental principle. It is the basis for hooks, callbacks, promises, configuring of complex objects etc.

How to make call to a JavaScript promise cleaner?

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.

How to use callback function in JavaScript functions

I am very new to JavaScript and need to use callback function in my java script function. I don't know how to use a callback function. Below is my code:
function SelectedFeature() {
// Here is my code call_Method1();
call_Method2();
}
The problem in the above function is that, call_method2() starts executing before call_Method1() ends its execution. To solve this problem, someone told me to use a callback function. Now how can I use callback function in my SelectedFeature() function? Please explain by using code sample.
I'm making an asynchronous request in call_method1(). I need call_Method2() should be called after completing execution call_method1(). But in my case, call_method2() calls before call_method1() completes its execution. Now how can I fix this?
You have to refactor call_method1() to accept and execute a callback after it finished execution:
call_method1(call_method2);
and
function call_method1(callback) {
// ...
// do asynchronous stuff, when the response is processed, call
if(typeof callback === 'function') {
callback();
}
// ...
}
Functions are first class citizens, so by referring to them by their name, you can pass them around like any other value.
We could help better if you post the code for call_method1.
What are you using to do your asynchronous call? Did you code it yourself or are you using a library like JQuery?
You could simply put a bool to say "working" that you set to true as method 1 starts and back to false when it finishes. you could then have method2 wait while working is true.
The question has already been answered above by Felix. Inspired by his answer and an issue I am having in a current project, I wrote a little gist that has a class that adds up a little extra safety.
To sum up, you pass a callback function just as the way you pass a variable. Then the receiver will trigger it as a function.
myCoolFunction: function( data ) {
// Do some thing with response
}
$.get( '/some/cool/url', myCoolFunction );
In the above $.get calls back myCoolFunction with the parameter data once the data is fetched
What happens if myCoolFunciton is a variable. Well it depends on how the receiver handles the input.
Just to be careful, I have a CoffeeScript class ( and its JavaScript compilation ) that will do some safety checks.
It doesn't do any thing magic, checks if its a function and returns, if not returns an empty function so that it would reduce possibility of JS error. https://gist.github.com/ziyan-junaideen/8717925

Can a callback have parameters defined?

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!");

Categories