Javascript return from nested function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
i have a function insde a function and im trying to return somehthing wich i return in the inner function.
function calculatePoints(){
request({
success: onWiktionaryResponseAvailable,
error: null,
url: "https://en.wiktionary.org/w/api.php?action=query&origin=*&format=json&titles="+inputWord,
});
function onWiktionaryResponseAvailable(result){
let wiktionaryEntry = JSON.parse(result),
keys = Object.keys(wiktionaryEntry.query.pages);
if (keys[0] === "-1"){
return 0;
}return inputWord.length;
}
}
i have tried to write: return onWiktionaryResponsAvailable(); but that doesn´t work in my case.

You've already got the idea of a "callback" function here when you call your request. You just need to carry that one step further, and pass in a callback function. (You could also accomplish the same thing with a Promise)
function calculatePoints(callback) {
request({
success: onWiktionaryResponseAvailable,
error: null,
url: "https://en.wiktionary.org/w/api.php?action=query&origin=*&format=json&titles=" + inputWord,
});
function onWiktionaryResponseAvailable(result) {
let wiktionaryEntry = JSON.parse(result),
keys = Object.keys(wiktionaryEntry.query.pages);
if (keys[0] === "-1") callback(0);
callback(inputWord.length);
}
}

Related

Returned object by function is empty [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I want return object with some data, but when I try return 'doc' variable, this variable is empty object.
here is my code:
myApp.factory('serviceDocuments', function serviceDocuments($http) {
var doc = {};
return {
getDocument: function (data) {
$http({
method: 'POST',
url: '/getDocument',
data: data
}).then(function successCallback(response) {
doc = response.data[0];
// in this place doc variable has needed data
}, function errorCallback(response) {
console.log("ups... ;(");
});
// in this place doc variable is empty object
return doc;
}
};
});
Your code is asynchronous. The line return doc is invoked before the callback for your http call (doc = response.data[0]).

How to prevent a Javascript function from returning a value till ajax method returns the value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am trying to validate if an email entered is present in the database or not and based on this result I execute a code. For this I am calling a Javascript function which calls ajax jquery method to a php page which checks id the email entered is present in database.
The code used is :
function validateEmail()
{ var username= document.getElementByName("email").value;
alert("Username is"+ username);
$.ajax({
type: "POST",
url: "emailCheck1.php",
data: "username="+username,
success: function(result){
if(result=="checked"){
return true;
}
else
{
document.getElementById("errorEmail").style.display="inline";
return false;
} }
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
But the problem is the function returns the value before ajax method completes. So the return value is not correct.
How can i make the function not return any value until ajax method completes and based on the return value of ajax method i return the required value...
Any help will be highly appreciated...
You need to use a callback to process the value once the ajax is finished, or make query synchronous (which is probably the wrong thing.)
You might look into function currying to specify your callback, if you want to set a parameter on the method.
See here
function partial(fn) {
// A reference to the Array#slice method.
var slice = Array.prototype.slice;
// Convert arguments object to an array, removing the first argument.
var args = slice.call(arguments, 1);
return function() {
// Invoke the originally-specified function, passing in all originally-
// specified arguments, followed by any just-specified arguments.
return fn.apply(this, args.concat(slice.call(arguments, 0)));
}
function doRequest()
{
callback = partial(doSomething, "Test Value");
$.post('action', {json_arg: "Test Arg"}, callback);
}

Factory that returns data after asynchronous call [duplicate]

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 8 years ago.
I have a service(factory) that uses another service to fetch data.Something like this:
factory('myFactory', function(anotherFactory) {
var factoryObject = {};
factoryObject.myMethod = () {
var newObjectToReturn;
// async call
anotherFactory.get(id, function(data) {
// do some processing
newObjectToReturn = data;
});
return newObjectToReturn;
}
return factoryObject;
});
Now, problem is of course, that because of asynchronous call, factoryObject.myMethod() always returns undefined, because return newObjectToReturn is first executed, and I can't simply return data. Is there any way around this ?
return the response data in callback
factory('myFactory', function(anotherFactory) {
var factoryObject = {};
factoryObject.myMethod = () {
var newObjectToReturn;
// async call
anotherFactory.get(id, function(data) {
// do some processing
newObjectToReturn = data;
},function(response){
return newObjectToReturn;
});
}
return factoryObject;
});

return value is undefined in node.js callback function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am writing a callback function in node.js but it is returning me an undefined value. Below is the code
exports.getRecord = (function(callback) {
return function(req, res) {
var recordName;
DBObject.record.find(jsonString, function(err, doc_record) {
doc_record.forEach(function(docRecordTravel) {
recordName = callback(docRecordTravel.recordCode);
console.log(recordName);
})
}
})(callbackFunc);
function callbackFunc(recordCode) {
var recordName;
DBObject.var_recordRack.find({
recordID: recordCode
}, function(err, record) {
record.forEach(function(recordLoop) {
recordName = recordLoop.recordName;
});
console.log("callback " + recordName);
return recordName
});
}
In callbackFunc it is showing me the recordName but when i return it it displays undefined. how can I return the value in call backs in node.js.
You can't.
It uses a callback function because it is asynchronous.
By the time the callback is called, the previous function has already finished and there is nowhere to return the value to.
If you want to do something with the data, then you must do it from the callback function.

Undefined return in $.get jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
This question is already answered and voted. My edits are related to making it clearer and share some new knowledge acquired for other developers, I'm not expecting new answers.
I'm reading an XML with jQuery, but when I try to show an alert it's fully working; however, when I try to return the value it always gives me a message that it's undefined.
function getText(value){
var val;
var lang;
var location;
lang=getLanguage();
if (lang=='en')
lang='';
else
lang+='.';
location="resources/AppResources."+lang+'xml';
$.get(location, function (xml) {
$(xml).find("data").each(function () {
var name=$(this).attr('name');
if (name===value)
return $(this).find('value').text();
});
});
}
This is the code that calls it:
$(document).ready(function() {
alert(getText('AppTitle'));
});
If I add an alert in the return statement it shows me the value selected.
Small update:
As Arun P Johny explained in his answer, the missed part in my code was the callback that are defined by Mozilla in this way:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
You can't return a value from a async method, the easiest solution is to use a callback function like this one:
function getText(value, callback) {
var val;
var lang;
var location;
lang = getLanguage();
if (lang == 'en')
lang = '';
else
lang += '.';
location = "resources/AppResources." + lang + 'xml';
$.get(location, function (xml) {
$(xml).find('data[name="' + value + '"]').each(function () {
callback($(this).find('value').text());
});
});
}
$(document).ready(function() {
getText('AppTitle', function(value){
alert(value);
})
});

Categories

Resources