I have two very basic functions in Javascript
function def(){
console.log("DEF")
}
function abc(){
setTimeout(function(){
console.log("ABC")
}, 1000)
def();
}
abc();
The above functions prints DEF and then ABC. I want to print them in order e.g. ABC and then DEF.
I have basic idea about callback but I am not getting as how to convert above functions to callback function to get the desired output :)
In JavaScript, functions are first-class members so you can pass them as parameters into other function just as you would any other object:
function def(){
console.log("DEF")
}
function abc(){
setTimeout(function(){
console.log("ABC")
}, 1000)
}
function withCallbacks(...callbacks) {
callbacks.forEach(callback => callback());
}
withCallbacks(abc, def); // prints DEF, ABC
According to my opinion the answer by #Mateusz is unnecessarily complicated.
If you want to send a callback to any function you have to send it as a parameter to that function.
// Function you want to send as a callback
function def(){
console.log("DEF")
}
// Function in which you want to call this callback
function abc(callback){
setTimeout(function(){
// Log ABC to the console
console.log("ABC");
// Call the callback function after the ABC has been logged
callback();
}, 1000);
}
// Call the function and pass your callback as parameter
abc(def);
Related
I've tried searching for this and cannot find the answer anywhere.
I've been using callbacks like this so far:
function one(param, callback){
//do stuff to param1
callback()
}
function two(param){
//do more stuff to param1
}
one(myParam, two)
This seems to work fine. However, I want to use three functions. This doesn't work:
function one(param, callback){
//do stuff to param1
callback();
}
function two(param, callback){
//do more stuff to param1
callback();
}
function three(param){
//do even more stuff to param1
}
one(myParam, two(three))
I'm guessing this is because of the brackets when passing two as a parameter in one, making 'two' excecute immediately.
How do I structure my code so I can excecute the function in the correct order?
This is because you setting three as a parameter of two:
function one(param1, callback){
alert(param1);
callback("Second Called", three);
}
function two(param1, callback){
//do more stuff to param1
alert(param1);
callback("Third Called");
}
function three(param1){
alert(param1);
//do even more stuff to param1
}
one("First Called", two);
You need to make little correction.
function one(param1, callback){
//do stuff to param1
// assuming param1 contains the processed value
callback(param1,three);
}
function two(param1, callback){
//do more stuff to param1
callback(param1);
}
function three(param1){
//do even more stuff to param1
}
// call the function like this
one(myParam,two);
Have a look on the library Async.js. Its good for handling asynchronous activity. You can better handle such cases and your code will be much more readable.
You could simply control the sequence of execution using an array and a forEach loop.
var callbacks = [one, two, three];
callbacks.forEach(function(callback){
callback(param);
});
Ofcourse the assumption here is that the scope of param is global to all of these callback functions.
function one(param, callback){
//param = "apple"
callback(param);
}
function two(paramFromOne){
//paramFromOne = "apple"
three(paramFromOne)
}
function three(paramFromTwoViaOne){
//paramFromTwoViaOne = "apple"
}
//you are invoking two before it can do anything inside the callback context of one
//one("apple", two(three))
//do this instead
one("apple", two)
If you want to specify callbacks that two uses you have to use a closure
function one(param, callback){
//param = "apple"
callback(param) //the callback here is the returned function in two
}
function two(callback){ //three
return function(paramViaOne) {
//paramViaOne = "apple"
callback(paramViaOne);
};
}
function three(paramFromTwoViaOne){
//paramFromTwoViaOne = "apple"
}
one("apple", two(three)) //two(three) returns an anonymous function that is used by one
If I want to break a callback implementation out of a method's parameter footprint for cleaner code I can do (for example)
foo.bar(a, callback(), b);
function callback() {
stuff;
}
instead of
foo.bar(a, function() {
stuff;
}, b);
But what do I do if the method passes something into the callback like three.js's loader functions? (http://threejs.org/docs/#Reference/Loaders/OBJMTLLoader)
foo.bar(callback(object));
function callback(object) {
object.stuff();
}
doesn't seem to work.
Got it. The format should be:
foo.bar(callback);
function callback(object) {
object.stuff();
}
The 2 snippets you've posted are actually different - when you pass an anonymous function as an argument it isn't run immediately, but in the "foo.bar" function itself. However, when you pass it as "callback()", that function runs immediately (it is useful in some cases, for example: if the function returns another function). So, pass it without "()".
For example:
function a(){
alert(1);
}
function b(callback){
callback(); //run the callback function.
}
b(a);
And, if you want to see an example of the second option:
function a(){
return function() {
alert(1);
};
}
a()(); //Alert
b(a()); //Alert
b(a) //nothing happens
How can I pass arguments to a callback function in this specific scenario.
I have a function that gets an object with callbacks like this
function doSomething({ callbackSuccess : myFunction, callbackError : myOtherFunction})
how can I pass arguments to myFunction or to myOtherFunction?
Like, if myOtherFunction gets a msg parameter like this
function myOtherFunction(msg) {
alert(msg);
}
Thanks in advance
Just like you pass them to any other function:
function doSomething(callbacks) {
callbacks.callbackSuccess('foo', 'bar');
}
If you mean you want to pass them "at the time of passing them into doSomething":
doSomething({ callbackSuccess : function () { myFunction('foo'); }, ... });
Simplest of all:
function dosomething(callback) {
//some code-poetry;
callback(1, 2, 3); //the callback is back!!!
}
function foo(a, b, c) {//this will be my callback
alert("I got some parameters")
}
dosomething(foo); //the function call
Best explanation for a callback function:Check this
A simple defination would be:the callback function is called at a certain point in the future when some code or a function completes execution.
Try this -
// function def
function doSomething(a) {
}
// calling function
doSomething({
callbackSuccess : function() {
myFunction(msg);
},
callbackError : myOtherFunction
});
How can an inner function call a parent function after it has expired?
setTimeout(main, 2000);
function main(){
/* .... code */
setTimeout(console.log("hello after 5 seconds"), 5000);
}
The intended action is to print hello after 5 seconds in 5 seconds (7 total); with the above code it prints it in 2 seconds.
You need to pass setTimeout function references. With setTimeout(console.log("hello after 5 seconds"), 5000);, you call console.log immediately. Any time you write () after a function name, you're invoking it.
console.log returns undefined, which is what is passed to setTimeout. It just ignores the undefined value and does nothing. (And it doesn't throw any errors.)
If you need to pass parameters to your callback function, there are a few different ways to go.
Anonymous function:
setTimeout(function() {
console.log('...');
}, 5000);
Return a function:
function logger(msg) {
return function() {
console.log(msg);
}
}
// now, whenever you need to do a setTimeout...
setTimeout(logger('...'), 5000);
This works because invoking logger simply returns a new anonymous function that closes over msg. The returned function is what is actually passed to setTimeout, and when the callback is fired, it has access to msg via the closure.
I think I understood what you want. Take a look:
var main = function(){
console.log("foo");
var function1 = function( string ) {
console.log("function1: " + string);
};
var function2 = function() {
console.log( "hadouken!" );
};
// you will need to use a closure to call the function
// that you want with parameters
// if you dont have parameters, just pass the function itself
setTimeout(function(){ function1("bar") }, 5000);
setTimeout(function2, 6000);
}
setTimeout(main, 2000);
Or:
function main(){
console.log("foo");
function function1( string ) {
console.log("function1: " + string);
};
function function2() {
console.log( "hadouken!" );
};
// you will need to use a closure to call the function
// that you want with parameters
// if you dont have parameters, just pass the function itself
setTimeout(function(){ function1("bar") }, 5000);
setTimeout(function2, 6000);
}
setTimeout(main, 2000);
I usually prefer the first sintax.
jsFiddle: http://jsfiddle.net/davidbuzatto/65VsV/
It works! You miss word function.
setTimeout(main, 1000);
function main() {
function function1 () { alert(1); };
setTimeout(function1, 1000);
}
It is maybe incredibly easy but I couldn't solve what was going on.
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
The only thing that actually confuses me is the a(num) part. What actually it does?Reminder: I really am asking because I'm not familiar with the javascript syntax.
When the function doSomething() is executed it is passed the parameter a,
a is also some function that is then called when setTimeout() expires after 1 second,
then calling the function a() passing the argument called num
Example usage:
// call doSomething() passing the test() function as an argument
doSomething(test);
// takes a number as an argument and shows an alert with that value
function test(number)
{
alert(number);
}
// takes a function as an argument that will perform a 1 second timeout then execute the function called a
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
It calls the function referenced by the variable a, using the value referenced by the variable num as an argument.
setTimeout returns a timeoutID which can be used to cancel it using clearTimeout, so if you run doSomething a lot of times you will get different integer numbers which represent different timeoutID.
In your case a must be a function so you can call it using the parameter num
Example:
function doSomethingElse (justANumber) {
return justANumber + 1;
}
// Here you call your function
doSomething(doSomethingElse);
// or another special case
doSomething(function (justANumber) {return justANumber + 1;});