Java script modify function at run time - javascript

enter code hereI have the following code
function a(){alert("a");}
I want to create a function b as
function b(){alert("a"); alert("b");}
My approach is something like
var b = a + alert("b");
This is of course not working. But I am wondering if there is some kind of library supporting this.
Edit: Maybe I need to describe my scenario so that its more clear what I want to achieve.
I am using async.js library to handler multiple async calls. My code looks like
var values = {};
...
function all() {
var allDfd = $.Deferred();
async.parallel(
[function (callback) {
remoteCall(function (result) {
values.v1 = result;
callback(null, 'one');
});
},
function (callback) {
remoteCall(function (result) {
values.v2 = result;
callback(null, "two");
});
},
function (callback) {
remoteCall(function (result) {
values.v3 = result;
callback(null, "three");
});
}], function (err, results) {
allDfd.resolve();
});
return allDfd.promise();
}
Clearly there are a lot of repetitive code that bothers me. So my idea is to create a function asyncCall to perform the boilerplate tasks. The idea is
var values = {};
...
function all() {
var allDfd = $.Deferred();
function getAsyncCall (func, innerCallback, callback) {
return function asyncCall(func, innnerCallback, callback){
func(innerCallback + callback(null)); // combine innerCallBack and callback code
}
}
async.parallel(
[getAsyncCall(remoteCall, function(result){values.v1=result;},callback),
getAsyncCall(remoteCall, function(result){values.v2=result;},callback),
getAsyncCall(remoteCall, function(result){values.v3=result;},callback),
], function (err, results) {
allDfd.resolve();
});
return allDfd.promise();
}
The line with the comment is what I am pondering. I am trying to create a new function that combines inner and outer callbacks.

You can do
var b = function() { a(); alert('b'); }

You could write:
var a=function(){alert("a");}
var b=function(){a(); alert("b");}
And to go a little further, you can even write a whole function composition function:
function compose( functions ) {
return function(){
for(var i=0; i!=functions.length; ++i) {
functions[i]();
}
};
}
var c=compose( [a, function(){ alert("b"); }] );
(See it at work at http://jsfiddle.net/xtofl/Pdrge/)

Related

How to call global function from promise function?

When performing the below function:
try {
Auction.deployed().then(function(contractInstance) {
contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
console.log("AUCTION HAS STARTED!!");
console.log(result);
updateAuction(result.receipt);
});
});
} catch (err) {}
}
};
updateAuction = function(data) {
console.log("UPDATE AUCTIONS!");
....
The updateAuction function is not called (even though the console.log functions are working correctly and displaying a message). How can I call the updateAuction function?
This is because of the order in which you're defining the promise and the function.
When you use the syntax updateAuction = function () {}, whether or not you use a var, you must define it above the promise code, otherwise it won't be available. This is in the same way that if you were to write the following, it wouldn't work:
var b = a;
var a = 'Hello!';
This seems quite obvious that a won't be available before it's defined. The same thing applies to functions:
var b = function () {
a();
}
var a = function () {
console.log('Hello');
}
The b function won't have access to a, because it's not yet defined.
If, however, you use the definition of function updateAuction() {}, it will be hoisted, meaning it is defined before anything else.
There are many articles regarding how hoisting works, for example this one from scotch.io and this from Mozilla
var updateAuction = function(data) {
console.log("UPDATE AUCTIONS!");
...
}
try {
Auction.deployed().then(function(contractInstance) {
contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
console.log("AUCTION HAS STARTED!!");
console.log(result);
updateAuction(result.receipt);
});
});
} catch (err) {}
You must define your function befor try. correct it like this
var updateAuction = function(data) {
console.log("UPDATE AUCTIONS!");
...
}
try {
Auction.deployed().then(function(contractInstance) {
contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {
console.log("AUCTION HAS STARTED!!");
console.log(result);
updateAuction(result.receipt);
});
});
} catch (err) {}
;

I need a way to execute an array of ajax calls wrapped in a function

The system I'm working with was designed to only make synchronous ajax calls, so i am looking for a workaround. First i have an ajax call that is wrapped in a function. I then wrap it in another function so it doesn't get executed when adding it to the array. So i have two arrays of async ajax call functions. I would like to execute everything in the first array, and then wait until everything has completed. I would then like to execute everything in a second array. This is what i have so far
I have a loop that goes through items and I have a wrap function for each item that takes in my already wrapped ajax call so that it doesn't get executed and stores it in an array like below
var postpromises = [];
var WrapFunction = function (fn, context, params) {
return function () {
fn.apply(context, params);
};
}
var postPromise = WrapFunction(ajaxFunction, this, [{
url: url,
data: j,
async: true,
type: 'POST',
success: function (data) {
//success
},
error: function (xhr, textStatus, errorThrown) {
//error
}
}]);
postpromises.push(postPromise);
I then have the same code for validation. So before I move on to next page, I have the following
$.when.apply(undefined, postpromises).then(function () {
console.log();
$.when.apply(undefined, validatepromises).then(function () {
console.log();
});
});
The issue is that when I get to the code above, none of my postpromises even get executed, so I feel like I may be missing something here.
Ideas?
The function $.when require a promise, in your code you are returning a function that return nothing, so just return the result of the wrapped function:
ES6 spread operator REF
function arguments object REF
var postpromises = [];
var validatepromises = [];
function f1() {
var fakePromise = $.Deferred();
setTimeout(() => {
fakePromise.resolve("IM RESOLVED!!");
}, 500);
return fakePromise.promise();
}
//OLD ONE
/*var WrapFunction = function (fn, context, params) {
return function () {
fn.apply(context, params);
};
}*/
var WrapFunction = function(fn, context, params) {
return function() {
return fn.apply(context, params);
}();
}
var postPromise = WrapFunction(f1, this, []);
postpromises = [postPromise];
var validatePromise = WrapFunction(f1, this, []);
validatepromises = [validatePromise];
//OLD ONE
/*$.when.apply(undefined, postpromises).then(function(res) {
console.log(res);
$.when.apply(undefined, validatepromises).then(function(res) {
console.log(res);
});
});*/
$.when.apply(null, [...postpromises, ...validatepromises]).then(function() {
console.log([].slice.call(arguments))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

self-executing anonymous functions and call it again

I want to do something like this:
var build= (function(){
//my function body
})();
function test(){
//somthing then call build
build() //i want to call build function again in my code
}
How can I do this?
I tried this in angular:
var buildRoot = (() => {
$SubNode.get({
TypeID: vendorAdminService.NodeType.Category
}, function(data: vendorAdminService.IGetNodeParameters) {
$scope.ProductTree = data.TreeNodeModelItem;
$scope.AjaxLoading = false;
}, function(err) {
// alert(err)
})
})();
$mdDialog.show(confirm).then(function() {
$Category.Remove(node.ID)
buildRoot
}, function() {
});
but it does not work.
Anybody can guide me??
You need to return a function in your IIFE.
If you IIF is not trivial and has many functionalities you could also consider using Reveal Module Pattern.
var build = (function() {
var f = function() {
console.log('hello');
};
f();
return f;
})();
function test() {
build();
}
test();
Just use a named function.
Your IIFE needs to return a function, for later calling. But then is no need for an anonymous function.
function build() {
//my function body
}
or
var build = function () {
//my function body
};
var build = (function() {
var init = function() {
// magic code
};
return {
init: init
}
}());
function test() {
build.init()
}
test();
You include all your functionalities inside your build object, and you'll be able to call them as soon as you return them from inside that object. This effectively is called the revealing module pattern
For more information, read this
I see that there are missing semi-colons ";"
$mdDialog.show(confirm).then(function() {
$Category.Remove(node.ID);
buildRoot();
}, function() {
});

Correct way to continue on after a generator function

I have the following generator function:
BulkLoader.prototype.load = function(password) {
var self = this;
return async(function * () {
try {
self.users = yield getJSON('/users');
self.contacts = yield getJSON('/contacts');
self.companies = yield getJSON('/companies');
return self;
} catch (err) {
throw err;
}
});
};
The asyc method looks like this, which I took from the Q library:
export default function async(generatorFunc) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return RSVP.Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return RSVP.Promise.resolve(result.value).then(callback, errback);
}
}
var generator = generatorFunc();
var callback = continuer.bind(continuer, "next");
var errback = continuer.bind(continuer, "throw");
return callback();
}
My calling code looks like this:
var bulkLoader = new GeneratorBulkLoader();
bulkLoader.load()
.then(render)
.catch(errorHandler);
This seems a bit weird having to work with promises after calling a generator function.
How do other people handle their calling code when working with generators?
This seems a bit weird having to work with promises after calling a generator function.
Why? The API is still a promise. Whether it did use generators internally does not make a difference.
How do other people handle their calling code when working with generators?
You can always use generators to sugar your calling code as well:
async(function* () {
var bulkLoader = new GeneratorBulkLoader();
try {
yield render(yield bulkLoader.load())
} catch(e) {
errorHandler(e);
}
});

System unique id of a function passed as a parameter (javascript)

This is probably not possible but maybe some of the stackoverflow geniuses can find a solution :)
W would like to have a function like this:
var myCrazyFunc;
myCrazyFunc = function (param1, callback) {
var funcId;
// I would like to get an Id of the function passed by callback
// which will be different for those two calls in example below
funcId = getFuncId(callback);
callback();
};
myCrazyFunc("param1", function () {
dosomething1;
});
myCrazyFunc("param1", function () {
dosomething2;
});
Please don't ask why I need that :) Simply it would simplify my code if that was possible.
Here is the function I made:
var myCrazyFunc;
var latestID = 0;
var funcToID = {};
function getFuncId(f) {
if (f in funcToID) {
return funcToID[f];
}
funcToID[f] = ++latestID;
return latestID;
}
myCrazyFunc = function(param1, callback) {
var funcId;
// I would like to get an Id of the function passed by callback
// which will be different for those two calls in example below
funcId = getFuncId(callback);
console.log(funcId);
callback();
};
myCrazyFunc("param1", function() {
'a';
});
myCrazyFunc("param1", function() {
'b';
});
this example would log:
1
2
I you run it with the same function code you get the same id, like here:
myCrazyFunc("param1", function() {
'a';
});
myCrazyFunc("param1", function() {
'a';
});
Ouput:
1
2
I hope that's ok.

Categories