javascript callback function - javascript

function make(callback) {
//some other manipulation to get data to pass it into $.post()
$.post(data, function(response) {
// do something
callback()
});
}
function two() {
make(function() {
console.log('hello');
});
}
console.log('hello') will still trigger first although I used callback. How to make make() run till everything is finished then trigger console.log('hello')?

Your code should work as soon as you call two().
This might visualize your situation better:
function requestSomething(callback) {
$.post(data, function(response) {
// do something
callback();
});
}
function callBackFunction() {
console.log('done!');
}
// Pass callBackFunction, which gets called after request.
requestSomething(callBackFunction);

Related

Callback on the function JS

I'm trying to make this work, what am I doing wrong?
I want to be able to do some stuff when function one is completed.
function one() {
// do stuff
}
function main() {
//script
//script
one(function() {
// do some stuff when "one" is completed
console.log("one is completed");
});
}
Why this doest fire a callback? (no log entry in the console)
You need to pass the callback as an argument and call it like normal function
function one(a, b, fn) {
// do staff
if (fn) {
fn()
}
}
function main() {
//script
//script
one(5, 6, function() {
// do some stuff when "one" is completed
console.log("one is completed");
}
}
Cause one does not expect a callback, therefore it will be ignored and never called back.
function one(callback) { // <- take a callback
callback(); // <- call back the callback "callback"
}
You need to pass the callback function inside the one() function. Then you need to call that function:
const one = (cb) => {
console.log('in one()');
cb();
}
const main = () => {
one(() => {
console.log('one() is completed');
});
}
main();
OUTPUT:
in one()
one() is completed

JavaScript Multiple Callback Function

I have been trying to figure out the Callback function feature in Javascript for a while without any success. I probably have the code messed up, however I am not getting any Javascript errors, so I supposed the syntax is somewhat correct.
Basically, I am looking for the getDistanceWithLatLong() function to end before the updateDB() begins, and then make sure that ends before the printList() function begins.
I have it working with a hardcoded "setTimeout" call on the functions, but I am overcompensating and forcing users to wait longer without a need if the Callback stuff would work.
Any suggestions? Below is the code:
function runSearchInOrder(callback) {
getDistanceWithLatLong(function() {
updateDB(function() {
printList(callback);
});
});
}
To accomplish this, you need to pass the next callback into each function.
function printList(callback) {
// do your printList work
console.log('printList is done');
callback();
}
function updateDB(callback) {
// do your updateDB work
console.log('updateDB is done');
callback()
}
function getDistanceWithLatLong(callback) {
// do your getDistanceWithLatLong work
console.log('getDistanceWithLatLong is done');
callback();
}
function runSearchInOrder(callback) {
getDistanceWithLatLong(function() {
updateDB(function() {
printList(callback);
});
});
}
runSearchInOrder(function(){console.log('finished')});
This code outputs:
getDistanceWithLatLong is done
updateDB is done
printList is done
finished
wouldn't this work:
function callback(f1, f2) {
f1();
f2();
}
As for passing arguments, be creative.
function1 = (callback1, callback2, callback3) => {
setTimeout(() => {
console.log("function 1 timed out!");
callback1(callback2, callback3);
}, 1500);
}
function2 = (callback1, callback2) => {
setTimeout(() => {
console.log("function 2 timed out!");
callback1(callback2);
}, 1500);
}
function3 = (callback1) => {
setTimeout(() => {
console.log("function 3 timed out!")
callback1()
}, 1500);
}
function4 = () => {
setTimeout(() => {
console.log("function 4 timed out!")
}, 1500);
}
function1(function2, function3, function4);
Just pass down the callbacks from the first function and execute each one, passing down the rest.
OUTPUT
function 1 timed out!
function 2 timed out!
function 3 timed out!
function 4 timed out!
In JavaScript, everything is an object, including functions. That is why you are able to pass callbacks as parameters - you are passing a function as if it were any other object.
In each function declaration, you need to run the callback.
function runSearchInOrder(callback) {
...
callback();
}
function getDistanceWithLatLong(callback) {
...
callback();
}
function updateDB(callback) {
...
callback();
}
Then your code posted above should work.

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

Javascript - make function tell the caller when function is finished

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
}
}

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