I have a function like this :
module.exports.download = function (cb) {
// Some Code
cb();
}
Is it the same to do this :
module.exports.copyimagefromalbumnext = function (callback) {
module.exports.download(callback);
}
or
module.exports.copyimagefromalbumnext = function (callback) {
module.exports.download( function () { callback(); } );
}
In advance thanks.
Is callback the same as function () { callback(); }
No. The second function neither cares about this context, passed arguments, nor the return value of an invocation. You could do
function() { return callback.apply(this, arguments); }
but that's just superfluous. Use the first approach and pass callback itself.
Related
Pulling my hair out here trying to understand the infuriating nuances of Javascript. Hopefully some JS guru can take a gander, point and go, "well, there's yer problem...".
Here's a slimmed down sample of the problem:
var Parent = (function () {
var func1 = function () {
func2(function (res) {
console.log(res);
});
};
var func2 = function (callback) {
callback('abc');
};
return {
init: function () {
func1();
func2();
}
};
})();
Call with Parent.init();
This fails with the error:
Uncaught TypeError: callback is not a function
at check2 (<anonymous>:9:9)
at Object.init (<anonymous>:15:13)
at <anonymous>:1:8
What's getting me, is that if I comment out the enclosing code, like so, then it works as expected:
// var Parent = (function () {
var func1 = function () {
func2(function (res) {
console.log(res);
});
};
var func2 = function (callback) {
callback('abc');
};
// return {
// init: function () {
// func1();
// func2();
// }
// };
// })();
...and call with func1();
Result:
abc
What am I missing?
Thanks
In your version, you're calling func2() without specifying the callback function, which is a required argument. In your second example (with init commented out), you're correctly specifying the callback function in func2(function (res) { ... });.
Is the below snippet something you're looking for?
const Parent = (function () {
const func1 = function () {
func2(function (res) {
console.log(res);
});
}
const func2 = function (callback) {
callback('abc'); // this is passing 'abc' to line 3 of this snippet
}
return {
init: function () {
func1();
// func2(); // you don't want to call "func2" here, as "func1" calls it
// Or you could run:
func2(function (res) {
console.log(res);
});
// But this makes "func1" redundant
}
};
});
Parent().init();
// Output
abc
You have to pass callback parameter into func2 inside init. something like this.
init: function () {
func1();
func2(function (res) {
console.log(res);
});
}
From a comment on the question:
I just want to know why it works in the one sample, but not the other.
Because in one example you pass an argument to func2 and in the other you don't. Look at the working version:
func2(function (res) {
console.log(res);
});
vs. the non-working version:
func2();
The difference is that the first one passes a function which gets invoked as callback('abc'); whereas the second one passes nothing, so the attempt to invoke the non-existant callback function fails.
As an aside, in your non-working example you call func2 twice, once with the callback and once without. So it both "works" and "fails" in that case.
I've created a working recursive for loop, but it only works if my callback has no arguments. I've tried callback(arguments) and callback(...arguments).
Thanks for any help you can provide!
function loopFunc (numOfSteps, callback) {
let i = 0;
if (i >= numOfSteps) {
let i = 0
return
}
callback()
loopFunc(numOfSteps - 1, callback)`enter code here`
}
It works if the callback takes no arguments:
function noArgsHello() {
console.log('hello')
}
const thisWorks = loopFunc(3, noArgsHello);
thisWorks()
It doesn't work if the callback takes an argument:
function sayHello (input) {
console.log(input)
}
const thisDoesntWork = loopFunc(3, sayHello('hello');
thisDoesntWork()
In this way:
const thisDoesntWork = loopFunc(3, sayHello('hello');
You are not passing a callback anymore, but you are executing the sayHello function and passing the returned value of that function to the loopFunc.
What you can do in these cases, is to use the bind method of functions for passing the function with arguments:
const thisDoesntWork = loopFunc(3, sayHello.bind(sayHello, 'hello'));
Or you can pass directly a function which executes your sayHello so that the argument is still a function and it will be used as callback inside your loopFunc:
const thisDoesntWork = loopFunc(3, () => sayHello('hello'));
You almost there! It depends what is your goal here, you can use either option:
function loopFunc (numOfSteps, callback) {
let i = 0;
if (i >= numOfSteps) {
let i = 0
return
}
callback(numOfSteps)
loopFunc(numOfSteps - 1, callback);
}
function printExtraStuff(greeting) {
return (val) => { console.log('greeting ', val)}
}
function printSteps(num) {
console.log(num);
}
var test1 = function() { loopFunc(3, printExtraStuff('hi there') )};
test1()
var test2 = function() { loopFunc(3, printSteps )};
test2()
You need to use an anonymous function if you want to pass parameters in an argument -based function (callback is an argument). Your code should instead be like this:
function sayHello(input) {
console.log(input)
}
const works = () => sayHello('hello');
works();
I want to Create an Anonymous function which will be called in another function. I tried this, why is it not working
function parent (i){
retrun function () {
console.log(i)
}
}
var anonym = parent(2);
function callback (fn){
fn();
}
callback(anonym);
there is spelling mistake in your return statement.. check return spelling,
function parent (i){
return function () {
console.log(i)
}
}
var anonym = parent(2);
function callback (fn){
fn();
}
callback(anonym);
function parent(i) {
function callback(fn);
alert("The function called 'function parent' has been called.");
}
function callback(fn) {
alert("The function called 'function callback' has been called.");
}
so i have a function which checks if a checksum is changed and if so it calls the callback which is provided by a parameter.
var watchFileChange = function watchFileChange(oldChecksum, callback){
// some code about checking checksum
if(oldChecksum != newChecksum){
callback()
}
}
exports.watchFileChange = watchFileChange;
my Jasmin specs looks like this.
var t = require('../server.js');
describe("watchFileChange", function() {
spyOn(t.watchFileChange, 'Callback');
var file_false = {
'foo.txt': 'd41dcccc8f00b204e9800998ecf8427e'
}
var file_true = {
'foo.txt': 'd41d8cd98f00b204e9800998ecf8427e'
}
function Callback() {
console.log("Callback Called")
}
it("Checksum is not right, it should call Callback function", function() {
watchFileChange(file_false, Callback);
expect(Callback).toHaveBeenCalled();
});
});
But it just doesn't work that way because Callback is not defined i get that. So my question is there a way to check if the by parameter provided callback is called?
You can create a fake object where you can define you callback function, and then pass it as the argument
var init = {
callback: function() {
console.log("Callback Called")
}
};
describe("watchFileChange", function() {
beforeEach(function() {
spyOn(init, 'callback');
});
//...
it("Checksum is not right, it should call Callback function", function() {
watchFileChange(file_false, init.callback);
expect(init.callback).toHaveBeenCalled();
});
});
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.