Use a function with parameters inside a callback - javascript

I've written a function which may take an unknown number of functions as parameters, but can't figure how I can make this work when one or more of the functions take parameters too.
Here is a quick example of what I would like to achieve:
function talk(name) {
console.log('My name is ' + name);
var callbacks = [].slice.call(arguments, 1);
callbacks.forEach(function(callback) {
callback();
});
}
function hello() {
console.log('Hello guys');
}
function weather(meteo) {
console.log('The weather is ' + meteo);
}
function goodbye() {
console.log('Goodbye');
}
// I would like to be able to do the following:
//talk('John', hello, weather('sunny'), goodbye);

You can pass an anonymous function which can call the function with required parameters
talk('John', hello, function(){
weather('sunny')
}, goodbye);
function talk(name) {
console.log('My name is ' + name);
var callbacks = [].slice.call(arguments, 1);
callbacks.forEach(function(callback) {
callback();
});
}
function hello() {
console.log('Hello guys');
}
function weather(meteo) {
console.log('The weather is ' + meteo);
}
function goodbye() {
console.log('Goodbye');
}
talk('John', hello, function() {
weather('sunny')
}, goodbye);

talk('John', hello, weather.bind(null, 'sunny'), goodbye);
In this case .bind is essentially returning a function with some bound parameters - quite analogous to Arun's answer, though you may consider this method a little more succinct / readable.

Related

Calling a namespaced callback function by name

This is probably basic... given a fully qualified function name, I'm trying to call it via .apply()
Superficial example
var ns = {
someFunc: function() { console.log('stuff'); }
}
function someTopLevelFunc() { console.log('top level'); }
Given a method that takes the name of that function, us there some way to call the namespaced function?
function theCaller(funcName) {
console.log("Callback name: " + callbackFunctionName)
const callbackFunction = window[callbackFunctionName];
console.log("Type: " + (typeof callbackFunction))
if((typeof callbackFunction) === "function") {
callbackFunction.apply(null, []);
}
}
theCaller('topLevelFunc');
theCaller('ns.someFunc');
The first call works while the second call shows the callbackFunction type as undefined
Probably a simple syntax issue, but my googling has failed me.

unpacking rest (...theArgs) parameter before passing it to the function

I am trying to call a function required number of times. To solve this, I am creating a function that takes rest parameters and iterating through the first argument. I am unable to unpack the rest arguments and pass it to the function. Is there a way that I could unpack and pass it to the function as parameters. Below is my working code. Is there a better way to make it work?
function hello(name) {
console.log("Hello "+ name);
}
function greet(name,time_of) {
console.log("Good " + time_of +" " +name);
}
function foo(times,x, ...args) {
for(i=0;i<times;i++) {
x(arguments)
//x(args); //works good for hello() but not for greet(). Doesn't pass them to second argument
x(args[0],args[1]); //This works but not scalable
//args.map((element) => x(element));
}
}
foo(2,hello,"Myname");
foo(3,greet,"Myname","Afternoon");
Just spread the args out again:
function hello(name) {
console.log("Hello " + name);
}
function greet(name, time_of) {
console.log("Good " + time_of + " " + name);
}
function foo(times, x, ...args) {
for (i = 0; i < times; i++) {
x(...args)
}
}
foo(2, hello, "Myname");
foo(3, greet, "Myname", "Afternoon");

Anonymous callback functions

So, I understand callback functions to a degree. For instance, I completely understand this:
function finalGuy(x) {
alert("Final Number: " + x);
}
function secondGuy(x, callback) {
x = x - Math.sqrt(x);
callback(x);
}
function firstGuy(callback) {
var x = parseInt(prompt("Enter a number"));
x *= x;
secondGuy(x, callback);
}
firstGuy(finalGuy);
However, when faced with something like this I can't seem to grasp it.
a(function () {
b(function () {
c()
})
});
Can someone please translate the first sequence of callbacks into a working example like the second one? Specifically, passing one result to the next callback similarly to how I did it in the first example.
These two produce the same result
1.
function acceptCallback(callback) {
callback();
}
function callback() {
console.log('callback invoked');
}
acceptCallback(callback); // => 'callback invoked'
2.
function acceptCallback(callback) {
callback();
}
acceptCallback(function() {
console.log('callback invoked');
});
In the first example you pass a function declaration, in the second example you pass an anonymous function
3. Performing operations in the scope of a callback to be passed to another callback, aka "callback hell"
Nothing special here, it's the same syntax as the first two examples. This is difficult to read for anyone.
function first(callback) {
callback('from first');
}
function second(callback) {
callback('from second');
}
function third(callback) {
callback('from third');
}
function fourth(n, callback) {
callback(n * 10);
}
first(function(fromFirst) {
var a = 5;
console.log(fromFirst); // 'from first'
second(function(fromSecond) {
console.log(fromSecond); // 'from second'
third(function(fromThird) {
console.log(fromThird); // 'from third'
var b = a + 5; // 10
fourth(b, function(fromFouth) {
console.log(a, b, fromFourth); // 5, 10, 100
})
});
});
});

How to hold the control in angularJS or JQuery or JavaScript

I have many services which gives data but takes time so is there a way to hold the control in angularJS or JQuery which will be executed once the other code will be finish.
Ex:
function fun1(){
// many functions get data
}
function fun2(){
// many functions get data
}
function fun3(){
// here I want to call fun1()
//once fun1() is executed then only call fun2()
}
Any idea how to achieve this in the angularJS?
Thanks in advance.
Callbacks would work:
function fun1(cb) {
// do stuff
cb();
}
function fun2() {
// do stuff
}
function fun3() {
fun1(fun2);
}
Or go with promises as outlined in the other answer.
You can use promises or $q
See here for more details https://docs.angularjs.org/api/ng/service/$q
function fun1(){
var deferred = $q.defer();
setTimeout(function() {
deferred.notify('About to greet ' + name + '.');
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deferred.promise;
}
function fun2(){
// many functions get data
}
function fun3(){
// here I want to call fun1()
//once fun1() is executed then only call fun2()
var promise = fun1();
promise.then(function() {
//called if fun1 return successfully
fun2();
}, function(reason) {
alert('Failed: ' + reason);
}, function(update) {
alert('Got notification: ' + update);
});
}
You cannot stop the code flow in javascript using any framework out there. What you are refering to is async code flow Which as referred by folks below can be done by promises or callbacks only

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.

Categories

Resources