Callback function for storing JSON to a variable [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I had a previous question where I was having issues for getting json from an url and storing it to a variable in order to pass it further to a function. I managed to get redirected to a solution that seemed promising, but it's still giving me undefined. The proposal was to use a callback as follows, but it doesn't seem to do the job.
var space = "";
function spaceCallback(data) {
fplan = data.space['space'];
}
function getSpace() {
var url = "http://localhost:8000/spaces/send_space/"
$.getJSON(url, function (data) {
spaceCallback(data);
});
}
I would need to pass space to blueprint3d.model.loadSerialized(space);.
What am I missing here?

Is it possible that you need to return your function?
function getSpace() {
var url = "http://localhost:8000/spaces/send_space/"
$.getJSON(url, function (data) {
return spaceCallback(data);
});
}
or ES6:
function getSpace() {
var url = "http://localhost:8000/spaces/send_space/"
$.getJSON(url, (data) => spaceCallback(data));
}

Related

Javascript return from nested function [duplicate]

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);
}
}

Why isn't my function returning my array? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
function getContent(type) {
var content = [];
$.get(`/${type}.json`, function(data) {
$.each(data, function(index, hash) {
content.push(hash);
});
// 1. content = [object, object, etc..]
});
// 2. content = []
return content;
}
I need help understanding this. Why is content empty on the 2nd comment? From the looks of it, the function starts pushing hash into a NEW variable called content, instead of referencing the content that I explicitly made in the beginning. How do I fix this? Why is javascript scope so confusing.
Also, to fix this, I global variables. WHY can my function have access to a global variable content anywhere in the function, but calling content in the beginning function, it won't have access to certain places.
Because $.get is async. The nature of this call is that it goes into the event loop and doesn't modify your current program flow.
You should use callback.
function getContent(type, callback) {
var content = [];
$.get(`/${type}.json`, function(data) {
$.each(data, function(index, hash) {
content.push(hash);
});
callback( content );
});
}
getContent("items", function( content ) {
console.log(content);
});
To give you a better example you can also use your flow, but it should look like this :
function getContent(type, callback) {
var content = [];
$.get(`/${type}.json`, function(data) {
$.each(data, function(index, hash) {
content.push(hash);
});
callback();
});
return content;
}
var items = getContent("items", function() {
console.log( items );
});

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;
});

How to return data from JQuery GET [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I made a function that runs a get request using JQuery.
But I need the get to return this received value to the calling function. function
gettime() {
var timeOut =0;
$.get("http://localhost:8080/t.html", function( data )
{
timeOut = data*1000;
return timeOut;
});
//retun(timeOut);
}
I want the value received by get to be returned to the main function that calls gettime()
please help out.
It's a integer am passing.
An idea could be implementing a callback:
function gettime(callback) {
var timeOut =0;
$.get("http://localhost:8080/t.html", function(data)
{
timeOut = data*1000;
callback(timeOut);
});
}
//Then you can retrieve that value by doing this:
gettime(function(timeout){
//Do your stuff here.
});

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