This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am new to Javascript, and Trying to write a function inside a function, but it always show undefine.
function csnotebook(){
function calculate_mw(peptide){
var total_mw=0;
var split_peptide = peptide.split("-");
// Check if the blog id is found in database
Aa.findOne({ three_letter: split_peptide[1] }, (err, aa) => {
// Check if the id is a valid ID
if (!aa) {
console.log("wrong aa");
}else{
total_mw += aa.mw;
}
return total_mw;
});
}
var publicAPI = {
mw: calculate_mw
};
return publicAPI;
}
var fred = csnotebook();
var totalmw = fred.mw("Ala-Cys");
console.log(totalmw);
I assume i can find the corresponding value mw from database, but totalmw, I always get undefined for some reson, anybody know why? Thank you!!
The inner function calculate_mw doesn't return anything, so the return value of a function is undefined unless you return something.
If you want to return the result of the Aa.findOne you should:
return Aa.findOne(...
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I will be the first to admit, I don't always get JS Promises. So if this is a stupid question I apologize in advance. =) Given the code below, I need to set a property in the class that contains this function (i.e. I need to call "this" within the fullfullment methods and have it refer back to the class.
I saw a few things that related to setting context, but they also required closures (()=>{...code..}) which don't work so well in Internet Explorer. And we can hate on that browser all we want but at the end of the day its a requirement that this code works in IE.
So my question today is, how do I get a reference to this passed into the methods below?
var result = this.saveChanges();
return Promise.resolve(result).then(function (value) {
return value.HasError === false;
}, function (value) {
if (value && value.responseJSON) {
return value.responseJSON.HasError === false;
}
return false;
});
Your assistance is appreciated immeasurably.
You can declare a variable that references this and use that in the function.
var self = this;
var result = this.saveChanges();
return Promise.resolve(result).then(function (value) {
self.someProperty = true;
return value.HasError === false;
}, function (value) {
if (value && value.responseJSON) {
return value.responseJSON.HasError === false;
}
return false;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I have to create a number of RabbitMQ channels in succession, so I am trying to parameterize their creation in a function whose return value would be the channel. The function is declared in the callback-of-a-callback to the connection function.
var otaChannel = null;
amqp.connect(amqp_url, (err0, conn) => {
if(err0) {
throw(err0);
}
function getConsumerChannel(channelname) {
conn.createChannel((err1, ch) => {
if(err1) {
throw(err1);
}
ch.assertQueue(channelname, '', (err, q) => {
console.log(' [*] Created ' + q.queue + '.');
return ch;
});
});
}
otaChannel = getConsumerChannel(otaQName);
});
If I do "console.log(ch)" in the assertQueue function, I see the details of the channel. However, otaChannel in the final line of the code is always null. I've tried a bunch of variations of the code I posted, but cannot get the channel assigned to otaChannel. Where am I going wrong?
This question already has answers here:
forEach/for...in not returning values? [duplicate]
(5 answers)
Closed 5 years ago.
I've checked other questions that seem to be duplicates but none of them have solved my problem. I have this simple function that loops through an array of rule objects and returns the one with the matching "type":
$ctrl.findRule = function(ruleName){
$ctrl.rules.forEach(function(rule){
if(rule.type === ruleName){
console.log("returning rule: " + rule.type);
return rule;
}
});
return null;
};
I call this function as follows:
var wordCountRule = $ctrl.findRule("word_count");
console.log(wordCountRule);
I see on the console returning rule: word_count and then the console.log(wordCountRule) displays undefined. I have tried everything and I have no idea why this is happening.
Thanks!
The issue is because you're returning the value from the inner forEach handler function, not your outer findRule() function.
To fix this you could define a variable to hold the return value and amend that within the inner scope:
$ctrl.findRule = function(ruleName) {
var returnVal = null;
$ctrl.rules.forEach(function(rule) {
if (rule.type === ruleName) {
returnVal = rule;
}
});
return returnVal;
};
However you should note that it you're looking for a single value you can use find() directly, without the need to loop explicitly:
$ctrl.findRule = function(ruleName) {
return $ctrl.rules.find(function(rule) {
return rule.type === ruleName;
});
};
Taking the above example a step further, by using ES6 syntax it can be reduced to just this:
$ctrl.findRule = ruleName => $ctrl.rules.find(rule => rule.type === ruleName);
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 6 years ago.
I have a basic function in protractor written as :
this.getCurrentUrl = function () {
browser.getCurrentUrl().then(function(url){
console.log('url : '+url);
});
};
Now is there a way I can access the 'url' outside of the inner function scope, because I need to return this value to some other function calling this one. I need to get the value and return it from outside of then(function(url){...}
the url will be acquired async, so you can't just assign it. You probably want to hand it a callback.
function handleUrl(url) {
// here is where you do something with the url
}
// let your callback be called
this.getCurrentUrl = function(fn) {
browser.getCurrentUrl().then( function (url) {
fn(url);
})
}
// make the call with your handler
this.getCurrentUrl(handleUrl);
Another approach is to have your function return a "container" and that gets inflated later. Then later you can check your container. Since the behavior is async, you won't know when it will be ready, so you can check for it on an interval or something...
// return a container object
this.getCurrentUrl = function() {
var urlContainer = {};
browser.getCurrentUrl().then( function (url) {
urlContainer.url = url;
});
return urlContainer;
}
var urlContainer = this.getCurrentUrl(); // starts off as an empty object
urlContainer.url // undefined
// then shortly in the future
urlContainer.url // has some url
Yet a third way is to return a closure
this.getCurrentUrl = function() {
var urlValue;
browser.getCurrentUrl().then(function(url) {
urlValue = url;
});
return function() {
return urlValue;
}
}
var getUrl = this.getCurrentUrl();
getUrl(); // initially, returns undefined;
// keep trying. then shortly in the future...
getUrl(); // now has the url