Access to a variable, which is output from an async function [duplicate] - javascript

This question already has answers here:
Saving data from the d3.js ajaxrequest in a variable to create axis with data
(2 answers)
Closed 7 years ago.
I have a problem with this snippet:
d3.csv("data/airports.csv", function(err, a) {
var count=0;
a.forEach(function(i){
if(i.iata_faa == ""){}
else {
count++;
addpoint(i.lon, i.lat,i);
}
});
airports=a;
myDataIsReady();
console.log(count);
});
function myDataIsReady(){
console.log(airports);
return airports;
}
console.log(airports);
Notice that airports is a global variable here.
I need to handle the variable airports for another function, but the value is null, I think that is null because the csv file has not yet been processed completely, right?
How I resolve it?

Generally for async functions, you push a callback (a function reference) into the async method, so that it processes the data when the ajax call completes. You don't return data from that type function, you inject data into it.

Related

Node js async fs.fileRead variable parsing [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 2 years ago.
I have the whole code wrapped by an async function, i'm using puppeteer basically.
If i use a simple fs.fileRead function, save the result of data inside a var then the code can read that variable in the next async function, and from my understanding it can read it exactly because is async same as the fs.fileRead function.
The problem comes when I try to do another fs.fileRead, way before the above, but in the same tree level, and try to read the variable saved inside it, in a if (){ statement right after, outside the fs.fileRead, I tried using a function but doesn't work either, below the example:
var fullcsv, filecsv;
fs.readFile('myfile.csv', (err, data) => {
if (err) {throw err;}
fullcsv = data.toString();
if(fullcsv.includes(urldom)){
filecsv = 0;
}else{
filecsv = 1;
}
processFile(filecsv);
});
var dog;
function processFile(filecsv) {
dog= filecsv;
}
console.log(dog);
if (urllink != "" && processFile() == 1){
...
The console says console.log(dog) is undefined , and the if statement turns out to be false cause it goes directlye to the else statement.
p.s. I also tried with fs.fileReadSync but does literally no difference at all.

Accessing Return Variable Declared in Callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
So I am going to preface this by saying that my understanding of callback functions is limited so there is a chance I am making a beginner mistake with either callbacks or RequireJS.
Essentially, what I am looking for is the ability to access the values of the method from an API and create a variable by looping through what is contained inside the callback function. I then want to take that variable and return its value in the return portion of my RequireJS define statement. Below is a simplified example of what I am trying to do.
//call an api library then loop through to get all values for your object
define(['apiLibrary'], function (api) {
//create var that contains api method of current object
var apiMethod = api.someMethod();
//declare value var to be used inside callback
var value ='';
//call otherMethod, specifying an arguement and use callback to access contents of method
apiMethod.otherMethod('arg',function (reply) {
//loop through each value inside callback
$.each(reply.item, function (key, value) {
//add values to variable for each instance of method
value += 'the key is '+key+' and the value is'+value;
});
});
//return some values as well as the value set above for the overall define method
return {
valueFromElsewhere: 'hardcoded for example',
valueFromLibrary: value //value is '' since it is set insde a callback function
}
});
I appreciate any help I get in advance! Thanks!
EDIT:
The information on promises is extremely helpful and definitely helps me wrap my head around asynchronous functions in general but I need to return my variable data in a RequireJS return statement. There is a downstream program, that I have no control over, expecting data to be returned in a specific format that is provided by the return value of my define function.
You'll need to access the value asynchronously. A great way of handling that is a Promise:
var getValue = new Promise(function(resolve, reject) {
apiMethod.otherMethod('arg',function (reply) {
$.each(reply.item, function (key, value) {
value += 'the key is '+key+' and the value is'+value;
});
resolve(value);
});
});
return {
valueFromElsewhere: 'hardcoded for example',
getValueFromLibrary: getValue
};
You can then access it using the .then api:
foo.getValueFromLibrary.then(function(value) {
console.log('Value:', value);
});

Read variable inside function in Javascript? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Right now I have three files, two javascript files and one html file that will call upon these two javascript files. Inside my first javascript file, let's call it part1.js, I have this content:
var dataval;
$.get('example.cgi', function(data){
dataval = data;
});
Inside part2.js, I am trying to call on this dataval value. But it is not working, as I am assuming that dataval is inside the get function and is therefore a local value. Is there anyway I can grab that value? My html file is calling on both of these javascripts. Is there anyway I can access that variable?
Thanks!!
There is a problem here with asynchronous calls. You should either use a callback function or make use of the jquery promise capability.
In your part1.js, you should instead define a function:
function callCgi(callback) {
$.get('example.cgi', callback); //Callback will receive the data.
}
and then use it in part2.js:
callCgi(function(data) {
//do something with data.
});
Or with promises:
function callCgi() {
return $.get('example.cgi');
}
and then use it in part2.js:
callCgi().then(function(data) {
//do something with data.
});

Unable to fetch object outside of function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the following code
function test(){
var api_url = "/Test/";
api.CFClient.load(api_url,function(success){
success.images; // Object with images
},function(error){
});
// More code to use the images returned.
I am basically unable to get the images from the success function. If i execute my code within the success function i am able to access the returned object. How do i store the returned object in a variable so i can use that object in my parent function and not the success function ?
I presume api.CFClient.load is asynchronous, and in that case you can't access success.images immediately in the test() function after invoking the load function. It will be available at some unknown time in the future, when the ajax request has completed. You'll have to invoke a different function from within your success callback and do whatever you need to do with success.images there, or else do what you need to do directly in the success callback function.
You need to account for the success function being asynchronous. You won't be able to use the returned images until the api call is complete. When it is, you can call another function and pass the images.
function test(){
var api_url = "/Test/";
api.CFClient.load(api_url,function(success){
useImages(success.images);
}, function(error){
});
function useImages(images) {
// do something with images here...
}
SO is full of errors like this(asynchronous workflow), just google for...
function test(){
var api_url = "/Test/";
function useImages(err, images) {
if (err) return console.error(err);
console.log(images);
}
api.CFClient.load(api_url,function(success){
useImages(null, success.images);
},function(error){
useImages(error);
});
}

Return object list Jquery Ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm calling a C# api through Jquery AJAX. I am able to loop through all of the data and print each in the console; however, I am not able return the data to a variable (var x) so that it contains all objects returned from the api call.
This is my code thus far:
var uri = 'api/products';
function test(){
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
var info = {};
$.each(data, function (key, item) {
// Add a list item for the product.
console.log(item);
info.append(item);
});
return info;
});
}
var x = test();
I have tried to just simply skipping the $.each() and returning data, with no luck.
Should I be using a method other than append? Or is there a way to just simply return data?
Thanks.
.done() is a promise (http://api.jquery.com/promise/), which takes a callback function. The callback function is void; nothing consumes its return...and the return in your code is the return for the (anonymous) callback function, not for test(), which is why you're seeing no value come out.
This is an asynchronous pattern. That means test() is going to return immediately, not waiting for the AJAX call to complete, and there's no value yet to put into x! The AJAX response will arrive later, at some unknown time. The purpose of the callback function is to allow you to (at that time!) do whatever it is you intend to do with the value you receive. You haven't shown us what that is in this example, but you're going to need to restructure it to happen after the promise is fulfilled.

Categories

Resources