Access function argument from anonymous function - javascript

How do I access version argument from within FetchData method below ?.
Note - Fetch data is an async Rest call which passes its data to callback function.
function TestData(guid, version) {
var data = '';
data = FetchData(guid, function (guid, msg) {
alert(version);
return getData(guid, msg);
}));
}

If you need it in the callback - this code is OK.
For example the result of this code will be alert('hello')
function TestData(guid, version) {
var data = '';
data = FetchData(guid, function (guid, msg) {
alert(version);
return getData(guid, msg);
});
}
function FetchData(guid, callback) {
$.get('http://www.example.com/', callback);
}
TestData('abc', 'hello');

Try to add version param to FetchData function.
This is simplest way.
function TestData(guid, version) {
var data = '';
data = FetchData(guid, version, function (guid, msg) {
alert(version);
return getData(guid, msg);
}));
}

Related

Web worker function return response two times for a single call

I am using web worker in my application to execute some operations. Calling the web worker function from my js file only once with parameter. But its executing twice, first time with out parameter (parameter 'undefined'). And second time with parameter. What am I doing wrong?
js File
function f1(data) {
console.log('function called');
ww.postMessage({ action: 'name', data: { params: data } });
ww.onmessage = function(event) {
res = event.data;
console.log(event.data);
};
}
in web worker file
self.addEventListener('message', function(e) {
functionName = e.data.action;
data = e.data.data;
switch (functionName) {
case 'name':
var res = processData(data);
self.postMessage(res);
break;
}
});
function processData(data) {
if (data.params != undefined) {
console.log('parameter', data);
//some code to run
//finally
return res;
}
}
The out put I am getting in console
function called
undefined // from event.data
parameter data //actual data I passed
{} //event.data result of the action
Why is the parameter data not consoled the first time.
You have some smaller errors in your code that prevents a smooth execution
1. you forgot to declare functionName and data as variables
self.addEventListener('message', function(e) {
var functionName = e.data.action;
var data = e.data.data;
switch (functionName) {
case 'name':
var res = processData(data);
self.postMessage(res);
break;
}
});
2. Your return value was never declared as variable as well
function processData(data) {
if (data.params !== undefined) {
console.log('parameter', data);
//some code to run
//finally
return data;
}
}
3. In your callback function you did not declare res as variable as well
var ww = new Worker('worker.js');
function f1(data) {
console.log('function called');
ww.postMessage({ action: 'name', data: { params: data } });
ww.onmessage = function(event) {
var res = event.data;
console.log(res);
};
}
f1('test');
I strongly advise to use a sophisticated IDE such as PHPStorm or WebStorm which give hints on such smaller (and bigger) errors, because they reference the whole application and therefore know where something is called and defined.

Get the value from callback function and set to parent function

I am new to Nodejs and javascript and working on nodejs api code. I am using GandiAPI to check domainAvaliablity(Project related requirement) and have created a get request method (checkDomainAvaliablity) like this.
exports.checkDomainAvaliablity = function (req, res) {
gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)
};
And I have a callback function which have 2 parameters(which I can not change).
I am able to get the value succesfully in my callback function.
Now I want to return "value" from callback and want to set in "res" paramameter of checkDomainAvaliablity function(Parent function) (something like res.json(task)) .
var callback = function (error, value) {
console.dir(value)
if (value[domain] == 'pending') {
console.log('result is not yet ready')
setTimeout(function () {
gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
callback)
}, 700)
}
else {
console.dir(value)
}
// I want to return "value" from here and want to set in "res" paramameter of checkDomainAvaliablity function (Parent function).
}
Note: Use of callbackfuncion is neccessary.
Thanks #trincot. Putting the callback function inside the parent function works fine.
exports.checkDomainAvaliablity = function (req, res) {
domain = req.params.domainAvaliablity
var callback = function (error, value) {
console.log("logging" + value + error)
if (value[domain] == 'pending') {
console.log('result is not yet ready')
setTimeout(function () {
gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
callback)
}, 700)
}
else {
res.send(value);
console.dir(value)
}
}
gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)
};

Reduce code redundancy in JS [Angular JS]

I am working with a angular application and i have the following functions.
Function 1
vm.getInfo = function () {
var infoKey = "INFO1";
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(function (response) {
return vm.infoResponse = response.data.texts;
});
}
vm.getInfo();
Function 2
vm.getDetails = function () {
var infoKey = "INFO2";
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(function (response) {
return vm.detailsResponse = response.data.texts;
});
}
vm.getDetails();
Both the above functions have similar behavior, but only the infoKey and the return value changes. Right now i have written the functions like this. This might sound very silly, but how can i optimize this function to reduce the code redundancy.
Make a common function that accept infoKey and then only return the response.data.texts and Handel the VM variable at the call back function.
function getInfo(infoKey) {
var url = "www.example.com" + infoKey;
var promise = datacontext.getData(url);
return promise;
}
Calling function should do something like:
getInfo(infoKey).then((response)=> {
vm.detailsResponse = response.data.texts;
},(err)=>{
//Handle errors here.
});
Or, you could simply send a callback to the getInfo function and handle it there.
vm.getDetails = function (infoKey) {
var url = "www.example.com" + infoKey;
return datacontext.getData(url)
.then(function (response) {
if(infoKey=="INFO1"){return vm.infoResponse = response.data.texts;}
else{ return vm.detailsResponse = response.data.texts;}
});
}
vm.getDetails(infoKey);
hope this help you.
You can try following things -
1) Get infoKey as parameter & return response.data.texts-
function get(infoKey) {
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(function (response) {
return response.data.texts;
});
}
2) Pass callable function as parameter to handle response -
function get(infoKey, handleResponse) {
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(handleResponse);
}
Using it like this -
get('Infokey1', function onResponse(response) {
vm.infoResponse = response.data.texts;
})

Use callback with javascript

I am creating project using javascript and nodejs. I am integrating callback in my function inside for loop with condition basis,but am unable to do this.my problem is callback is completed on first iteration of loop. here is my code:
function tagEndpointNames(callback) {
var data = userGenerateToken();
var sql = "SELECT * FROM topology_data WHERE topology_coordinates !='' and topology_uuid is not null"
var query = conn.query(sql, function(err, tagEndpointNames) {
for (var i = 0; i < tagEndpointNames.length; i++) {
var topologytagData = {
"topology_tag": tagEndpointNames[i].topology_uuid
}
var tpCooridinates = JSON.parse(tagEndpointNames[i].topology_coordinates);
for (var j = 0; j < tpCooridinates.stageObjects.length; j++) {
if (tpCooridinates.stageObjects.length) {
if (tpCooridinates.stageObjects[j].endPointId) {
if (isGuid(tpCooridinates.stageObjects[j].endPointId)) {
var endPointUUID = tpCooridinates.stageObjects[j].endPointId;
var _ro = require('request');
var url = url;
var _d = '';
_ro({
url: url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + data['access_token']
},
json: topologytagData
}, function(_e, _r, _b) {
if (_r.statusCode == 200 && !_e) {
callback()
//return;
} else {
callback()
console.log("andarss")
return;
}
})
}
}
}
}
}
})
}
Here is the function call:
tagEndpointNames(function(){
console.log ('Server Closed during MIGRATION JOB 4');
server.close(function () {
process.exit(0);
});
})
When you are running asynchronous process with callback in a for loop, remember that the callback from callee will be fired in the first event completed inside the loop. In your case request lib call is an asynchronous process inside for loop, you need to handle all callback from all the request call before you want to callback the callee.
Please read:
How to write asynchronous functions for Node.js
Maybe it's time for you to start using Javascript Promise.
The async library for Node will help you for doing this kind of tasks.
Use async waterfall.It Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.
js
var create = function (req, res) {
async.waterfall([
_function1(req),
_function2,
_function3
], function (error, success) {
if (error) { alert('Something is wrong!'); }
return alert('Done!');
});
};
function _function1 (req) {
return function (callback) {
var something = req.body;
callback (null, something);
}
}
function _function2 (something, callback) {
return function (callback) {
var somethingelse = function () { // do something here };
callback (err, somethingelse);
}
}
function _function3 (something, callback) {
return function (callback) {
var somethingmore = function () { // do something here };
callback (err, somethingmore);
}
}
Reference

Run code after function completes and get returned value

Imagine i have a simple javascript function:
function someFunction(integer)
{
data = integer + 1;
return data;
}
I need to call this from inside another function and use the returned value:
function anotherFunction(integer)
{
int_plus_one = someFunction(integer);
//Do something with the returned data...
int_plus_two = int_plus_one + 1;
return int_plus_two;
}
How can i ensure that the return of anotherFunction return is only returned after someFunction completes? It actually seems to work ok with very fast functions like these. However if someFunction has to do some ajax lookups, the return of aotherFunction fails.
Thanks,
Steve
You do not know when or even if an asynchronous function will complete. The only way to handle this is to use a callback function, a function that gets executed after the async operation has completed.
This was my "aha!" moment: How to return the response from an asynchronous call?
As far as your code is sync, the approach above is fine.
Once you start introducing async parts, the one below involving callbacks is a common used approach:
function fn (v, cb) {
doSomethingAsyncWithV(function (err, _v) {
if(err) return cb(err);
cb(null, _v);
})
}
function yourFirstFn () {
var v = 0;
fn(v, function (err, _v) {
// do here whatever you want with the asynchronously computed value
});
}
How about promise? With that in mind, there's no need to worry about callback. It's one of the cool things in AngularJS.
var q = require('q');
var myPromise =function() {
var deferred = q.defer();
setTimeout(function(){
var output = anotherFunction(1);
deferred.resolve(output)
}, 10000); // take times to compute!!!
return deferred.promise;
}
var objPromise = myPromise();
objPromise.then(function(outputVal){
console.log(outputVal) ; // your output value from anotherFunction
}).catch(function(reason) {
console.log('Error: ' + reason);
})
then is ONLY exeucted after promise has been resolved. If an exception or error is caught, the catch function executes.
how about this?
function someFunction(integer, callback)
{
data = integer + 1;
return callback(data);
}
function anotherFunction(integer)
{
int_plus_one = someFunction(integer, function(data){
int_plus_two = int_plus_one + 1;
return int_plus_two;
});
//Do something with the returned data...
}
You could use promises:
new Promise(function someFunction(resolve, reject) {
ajaxLib.get(url, options, function (data) {
resolve(data);
});
}).then(function anotherFunction(integer)
{
int_plus_one = integer;
//Do something with the returned data...
int_plus_two = int_plus_one + 1;
return int_plus_two;
});
If you use jQuery, $.ajax returns a thenable :
$.ajax(url, options).then(function processDataFromXHR(data) {
return data.integer;
}).then(function anotherFunction(integer){
int_plus_one = integer;
//Do something with the returned data...
int_plus_two = int_plus_one + 1;
return int_plus_two;
});

Categories

Resources