Javascript - make function tell the caller when function is finished - javascript

So let's say I'm calling a function like so:
some_function('pages',{attr1: 1, attr2: 2},function(){
alert('the function is ready!');
}
Now how do I set up the "some_function()" function in order to return to the caller that it is ready and make the alert go off?
Thanks :)

I think you mean callbacks.
Maybe something like this:
function some_function(param1, param2, callback) {
// normal code here...
if ( typeof callback === 'function' ) { // make sure it is a function or it will throw an error
callback();
}
}
Usage:
some_function("hi", "hello", function () {
alert("Done!");
});
/* This will do whatever your function needs to do and then,
when it is finished, alert "Done!" */
Note: Put your return after the if clause.

Do you mean something like this?
function some_function(type, options, callback) {
if (some_condition) {
callback();
}
}

Assuming the signature for some_function looks like this:
function some_function(name, data, callback)
You just need to call callback when you're ready to.
function some_function(name, data, callback){
// do whatever
if(typeof callback === 'function'){
callback(); // call when ready
}
}

Related

Writing a function with a callback

Lets imagine that I have some code:
var someString = "";
function do1(){
doA();
doB();
}
function doA(){
// some process that takes time and gets me a value
someString = // the value I got in prior line
function doB(){
//do something with someString;
}
What is the correct way to make sure somestring is defined by doB tries to use it? I think this is a situation that calls for a callback, but I'm not sure how to set it up?
Usually, I have solved this problem like following code by callback parameter. However, I don't know this is correct answer. In my case, it's done well.
var someString = "";
function do1(){
doA(doB);
}
function doA(callback){
// some process that takes time and gets me a value
someString = // the value I got in prior line
callback();
}
function doB(){
//do something with someString;
}
I usually write these such that the function can be called with, or without, the callback function. You can do this by calling the callback function only if typeof callback === 'function'. This allows the function which includes the possibility of a callback to be a bit more general purpose. The call to the callback(), obviously, needs to be from within the callback of whatever asynchronous operation you are performing. In the example below, setTimeout is used as the asynchronous action.
var someString = "";
function do1() {
doA(doB); //Call doA with doB as a callback.
}
function doA(callback) {
setTimeout(function() {
//setTimeout is an example of some asynchronous process that takes time
//Change someString to a value which we "received" in this asynchronous call.
someString = 'Timeout expired';
//Do other processing that is normal for doA here.
//Call the callback function, if one was passed to this function
if (typeof callback === 'function') {
callback();
}
}, 2000);
}
function doB() {
//do something with someString;
console.log(someString);
}
do1();
You can, of course, do this without using a global variable:
function do1() {
doA(doB); //Call doA with doB as a callback.
}
function doA(callback) {
setTimeout(function() {
//setTimeout is an example of some asynchronous process that takes time
//Simulate a result
var result = 'Timeout expired';
//Do other processing that is normal for doA here.
//Call the callback function, if one was passed to this function
if (typeof callback === 'function') {
callback(result);
}
}, 2000);
}
function doB(result) {
console.log(result);
}
do1();
function someFunctionA(callback){
var someString = "modify me";
callback(someString);
}
function someFunctionB(someString){
// do something
}
function main() {
someFunctionA(somefunctionB);
}

call a callback in other callback js

I wondering if we can set a function containing a Callback function as parameter to another function who takes a callback too.
Example
function save(err, data, cb){};
function get(id, cb){};
get('12', save)?
Of course, a variable can be passed as argument of a function!
It may be clearer for you if you do:
// This also works with the notation `function save(...)`
var save = function(err, data, cb) {
alert('save' + err); // save12
},
get = function(id, cb) {
alert('get' + id); // get12
cb(id); // This call the "save" function
}
;
get('12', save);
Just be careful to not stack your callback too much or you will enter in the callback hell world!
Yes you can, check this example:
jsFiddle Example
jQuery(document).ready(function () {
function1({
param: "1",
callback: function () {
function2({
param : "2",
callback: function(){
alert("hello");
}
})
}
});
});
function function1(params){
alert(params.param);
params.callback();
}
function function2(params){
alert(params.param);
params.callback();
}
I hope it will be useful.

Get variable out of anonymous javascript function

I'm using an anonymous function to perform some work on the html I get back using Restler's get function:
var some_function() {
var outer_var;
rest.get(url).on('complete', function(result, response) {
if (result instanceof Error) {
sys.puts('Error: ' + result.message);
} else {
var inner_var;
// do stuff on **result** to build **inner_var**
outer_var = inner_var;
}
});
return outer_var;
}
How can I get the value of inner_var out to the some_function scope and return it? What I have written here doesn't work.
The get call is asynchronous, it will take some time and call your callback later. However, after calling get, your script keeps executing and goes to the next instruction.
So here is what happens:
you call get
you return outer_var (which is still undefined)
... sometimes later ...
get result has arrived and the callback is called.
outer_var is set
You can't have your some_function return a value for something that is asynchronous, so you will have to use a callback instead and let your code call it once data is processed.
var some_function(callback) {
rest.get(url).on('complete', function(result, response) {
if (result instanceof Error) {
sys.puts('Error: ' + result.message);
} else {
var inner_var;
// do stuff on **result** to build **inner_var**
callback(inner_var);
}
});
}
Like most of the modules of node, Restler is also a event based library having async calls. So at the time you do return outer_var; the complete callback was not necessarily called (With some libraries it could be if it the result was cached, but you should always expect that it is called asynchronous).
You can see this behavior if you add some logging:
var some_function() {
var outer_var;
console.log("before registration of callback"); //<----------
rest.get(url).on('complete', function(result, response) {
console.log("callback is called"); //<----------
if (result instanceof Error) {
sys.puts('Error: ' + result.message);
} else {
var inner_var;
// do stuff on **result** to build **inner_var**
outer_var = inner_var;
}
});
console.log("after registration of callback"); //<----------
return outer_var;
}
So if you would like to do something with this value you would need to call the function that should do something with this value out of your complete callback.
Remove the var outer_var; from your function some_function;
Declare the var outer_var; upper then your function
It should be work after you did step 1, not really need step 2.

javascript inline callback function to separate function

Why is this code working:
function onCordovaReady() {
navigator.globalization.getLocaleName(function (locale) {
jQuery.i18n.properties({
name:'message',
path:'lang/',
mode:'map',
language:locale.value,
callback: function(){
alert(locale.value);
alert(jQuery.i18n.prop('msg_hello'));
alert(jQuery.i18n.prop('msg_complex', 'John'));
}
});
});
}
And this one not:
function onCordovaReady() {
navigator.globalization.getLocaleName(function (locale) {
jQuery.i18n.properties({
name:'message',
path:'lang/',
mode:'map',
language:locale.value,
callback: onLanguageReady(locale)
});
});
}
function onLanguageReady(locale) {
alert(locale.value);
alert(jQuery.i18n.prop('msg_hello'));
alert(jQuery.i18n.prop('msg_complex', 'John'));
}
I want to make the callback in a different function so my code will look cleaner, but couldn't get it to work. The first alert will work (it will display nl_NL), but the second and third alert will output [msg_hello] and [msg_complex].
Many thanks!
Try with this:
// beginning of code omitted
callback: function(locale) {
onLanguageReady(locale)
}
it is because you are assigning undefined to the callback property.
You are calling onLanguageReady and assigns that value to the callback method.
The solution is to use another function as callback function which will call the onLanguageReady function as given by #romainberger
function onCordovaReady() {
navigator.globalization.getLocaleName(function (locale) {
jQuery.i18n.properties({
name:'message',
path:'lang/',
mode:'map',
language:locale.value,
callback: onLanguageReady
});
});
}
function onLanguageReady(locale) {
alert(locale.value);
alert(jQuery.i18n.prop('msg_hello'));
alert(jQuery.i18n.prop('msg_complex', 'John'));
}
will work if the function calls back with locale.
the callback is expecting a function pointer that it can call once the processing is done when you say onLanguageReady(locale) you are actually executing the function and thus assigning the result of the function as the call back in this case the return is nothing thus undefined

Adding callback functionality to my simple javascript function

I am not writing a plugin. I am just looking for a simple clean way to let myself know when a certain function has finished executing ajax calls or whatever.
So I have this:
function doSomething() {
...
getCauses("", query, function () {
alert('test');
});
...
}
function getCauses(value, query) {
//do stuff...
}
Of course the alert never happens. I have a $.ajax call inside getCauses and would like to alert or do some action after getCauses finishes executing and then running the line of code from where the function was called.
Ideas? Thanks.
You first need to add the parameter to getCauses:
function getCauses(value, query, callback) {
}
Then, inside of your $.ajax call, call the callback parameter in your AJAX completion callback:
$.ajax({
// ...
complete: function() {
// Your completion code
callback();
}
});
You're passing your callback function but not executing it.
function doSomething() {
...
getCauses("", query, function () {
alert('test');
});
...
}
function getCauses(value, query, callback) {
//do stuff...
//stuff is done
callback();
}
Just using a bit of javascript trickery, here's an implementation that will allow you to implement some default functionality, in the case that no callback is defined. This would be great if 99% of the time you want a generic callback, and then you simply want to customize it in a few places.
var my_callback = function() {
alert('I am coming from the custom callback!');
}
var special_function(string_1, callback) {
(callback || function() {
// Default actions here
alert('I am coming from the generic callback');
})();
}
// This will alert "I am coming from the custom callback!"
special_function("Some text here", my_callback);
// This will alert "I am coming from the generic callback"
special_function("Some text here");
// This will do nothing
special_function("Some text here", function() {});
Cheers!

Categories

Resources