Reading Array of Json [duplicate] - javascript

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 2 years ago.
I have created a function that tries to get lat long based on the address and after that, I want those to print on console
How to get values of coords.... am I doing it in the correct way? please help to understand it.
coords = getLocationCoords("Ambala,Haryana,India,134003");
console.log(coords)
function getLocationCoords(fa){
var coords = [];
$.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q='+fa, function(data){
coords['lat'] = JSON.parse(data[0].lat);
coords['lon'] = JSON.parse(data[0].lon);
});
return coords;
}//getLocationCoords

You cannot get the coords as "returned value", because there is nothing to return. That is, nothing to return until some handler is invoked, which could be 0.2 seconds later, or 3 seconds later. But if the handler returns it, you still won't be getting it since the assignment happened immediately. To solve this, you can also just make it a "promise", so that when the value is ready, you can then() it, and process the value, like follows:
getLocationCoords("Ambala,Haryana,India,134003")
.then(data => {
coords = data.map(loc =>
({
lat: Number(loc.lat),
lon: Number(loc.lon)
})
);
console.log("GOT IT", coords);
});
function getLocationCoords(fa) {
return $.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q=' + fa)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Javascript - var values not changed inside callback? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
Why does changing the values of status and output inside the callback of a function I await for doesn't change their values outside?
var status = '';
var output = '';
if (orderTranscription != "TRANSCRIPTION_ERROR") {
await runPython38Script ("processing.py", orderTranscription, (output) => {
const orderInfo = JSON.parse(output);
// Both of these have a value defined here when I console.log, not empty string
status = orderInfo.status ? "VALID" : "PROCESSING_ERROR";
output = orderInfo.output;
});
}
// When I try to console.log outside, I get empty string.
console.log(status);
console.log(output);

Return value from callback is null. How can I structure my code to get the return value correctly? [duplicate]

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?

How to return a value after ajax call? [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 to return a ajax call value to other function. Code shown below
script
var obj2 = ajax_call();
function ajax_call() {
var obj3;
$.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){
obj3 = $.parseJSON(data);
});
return(obj3);
}
console.log(obj2+'test');
function ajax_call() {
return $.post("action.php",{action: 'view_style_code_action',style_val: v},function(data,status){
return data;
});
}
var obj2 = ajax_call();
console.log(obj2+'test');
AJAX returns result in future (that's why it is asynchronous). Since JavaScript runs in a single thread, you cannot return a value immediately.
You need to understand jQuery's Promise API instead, which $.post already supports.
Modify your code a bit to leverage the power of promises in your code.
function ajax_call() {
return $.post("action.php", {action: 'view_style_code_action',style_val: v})
}
ajax_call()
.then(function(data) {
// Do the parsing here
var obj3 = $.parseJSON(data);
// Do rest of your work here.
...
});

How to get variable value outside angular function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have been hours trying to understand why I don't get the value of a variable, outside an Angular.js function. First I get the value from a Firebase database, here is my reference :
var refspaedtServ = new Firebase(FBURLSPA + $routeParams.id);
$scope.spaedServ = $firebaseObject(refspaedtServ);
Then I have the function:
///// IMAGE REFERENCE ////
var lafoto = '';
refspaedtServ.on("value", function(rootSnapshot) {
lafoto = rootSnapshot.val().foto;
console.log("Inside image ", lafoto)
});
As you can see, I define my variable 'lafoto' as global
With the console.log Inside image, I can see the value is correct
But when I try to get the value of "lafoto" variable, outside the function, I'm getting "undefined", I mean no value.
console.log("Outside Image ", lafoto)
It seems silly, but I'm reaching madness for that.
Can anybody give me a hint please?
Regards,
Victor
It's pretty simple, let's see it by your code, assuming your function in the 'value' event needs 1500ms to complete:
var lafoto = '';
console.log('start');
//listening for the event
refspaedtServ.on("value", function(rootSnapshot) {
//after ~1500ms...
lafoto = rootSnapshot.val().foto;
console.log("Inside", lafoto)
});
console.log('outside', lafoto); //executed immediately
In console, you will receive as result:
'Start'
'outside'
'inside'
that's because you are waiting asynchronously for the event: hence, "outside" the .on function you are executing the code before the code inside.
So, your variable lafoto will always result undefined, because it has not been already assigned.
.
Edit 1
You can use a callback function to perform code after the .on event:
var lafoto = '';
console.log('start');
//listening for the event
refspaedtServ.on("value", function(rootSnapshot) {
//after ~1500ms...
lafoto = rootSnapshot.val().foto;
console.log("Inside", lafoto)
myAfterFunction();
});
function myAfterFunction(){
console.log('myAfterFunction', lafoto);
}
console.log('outside', lafoto); //executed immediately
In console, you will receive as result:
'Start'
'outside'
'inside'
'myAfterFunction'

js function inside function and wait for return value [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.
$(document).ready(function(){
// Global function (will be include in any HTML file)
function m3_result(size_1, size_2, size_3){
$.get('http://www.google.com', function(data){
return data;
});
}
// Another function
function calculate(){
var size_1 = parseFloat($('#add_document_form #size_1').val());
var size_2 = parseFloat($('#add_document_form #size_2').val());
var size_3 = parseFloat($('#add_document_form #size_3').val());
var ax = m3_result(size_1, size_2, size_3);
alert(ax); // Here ax return: UNDEFINED
}
// Run
calculate();
});
Results are "undefined", but I would like that calculate() will wait for m3_result() to execute. I see that here problem is coming when I added $.get(), but its needed...
I have searching for callback() like functions, but none fit to my needs, or I just didnt put that right.
Any help will be highly appreciated, thanks.
GET url will be localy and element IDs are also ok.
You can't return a result from an asynchronous function, instead you can return a promise to supply that value later, which as it happens is the jqXHR object returned by $.get:
function m3_result() {
return $.get(...)
}
and do the same in calculate:
function calculate() {
...
return m3_result(...);
}
and then wait for the result, which will be passed as a parameter to the callback registered with the .done function:
calculate().done(function(result) {
alert(result);
});

Categories