I'm using request to get data from json. But, I don't know how to pass variable.
request.get('http://domain/to.json', function (error, response, body) {
var json_body = JSON.parse(body);
});
console.log(json_body);
But, json_body is not defined.
Put your console.log() inside the request callback or create a separate function for your console.log() and call that from your request callback. There's lots of different ways to go about it (you might look into the async module if you're doing a lot of asynchronous function calls together).
Related
i am newbie en react technologie.
how can i get the json data from http request ?
as you can see on
i can get the value of console.log(dataExt); from inside this function,
but i can not get the value of console.log(dataExt); from outside this function.
i miss something ?
i did use return dataExt; why i get nothing ?
i have modified my function:
async function getDataExt()
{
try {
let response = await fetch('https://xxxx');
let dataExt = await response.json();
console.log(dataExt);
return dataExt;
} catch(error) {
console.error(error);
}
}
but still i can not get the value
The fetch call is asynchronous and returns a Promise, that's why you need to call then to get the result. As it stands, line 62 will not wait for the fetch in getDataExt() to complete before running the console.log. You need to treat getDataExt as an async function and either do async/await or .then().
It is because of the asynchrony, that is, the "return" is executed when it obtains the value in the request it makes, and that takes time. Let's say it takes 1 second for the data to return, but 0.1 for the variable to print, that means it prints first and then assigns the value. Now, a possible solution would be to create a "state" to save that data or how the partner said, create the function getDataExt as an asynchronous function.
I am trying to return an array of data inside a JSON object that is return from a URL, I can see the data that is being returned using console.log.
However when trying to catch the return array in a variable for example:
var arr = list();
console.log(arr.length);
The length being output by this code is "0" despite the fact that the data returned has content (so the length is greater than zero). How can I use the data?
list: function() {
var grades = [];
$.getJSON(
"https://api.mongolab.com/api/1/databases", function(data) {
console.log(data);
grades [0] = data[0].name;
console.log(grades.length);
});
return grades;
},
The issue you are facing is easy to get snagged on if you aren't used to the concept of asynchronous calls! Never fear, you'll get there.
What's happening is that when you call the AJAX, your code continues to process even though the request has not completed. This is because AJAX requests could take a long time (usually a few seconds) and if the browser had to sit and wait, the user would be staring in angsuish at a frozen screen.
So how do you use the result of your AJAX call?
Take a closer look at the getJSON documentation and you will see a few hints. Asynchronous functions like getJSON can be handled in two ways: Promises or Callbacks. They serve a very similar purpose because they are just two different ways to let you specify what to do once your AJAX is finished.
Callbacks let you pass in a function to getJSON. Your function will get called once the AJAX is finished. You're actually already using a callback in the example code you wrote, it's just that your callback is being defined inside of your list() method so it isn't very useful.
Promises let you pass in a function to the Promise returned by getJSON, which will get called once the AJAX is finished.
Since you are doing all this inside of a method, you have to decide which one you're going to support. You can either have your method take in callbacks (and pass them along) or you can have your method return the promise returned by getJSON. I suggest you do both!
Check it out:
var list = function(success) {
// Pass in the callback that was passed into this function. getJSON will call it when the data arrives.
var promise = $.getJSON("https://api.mongolab.com/api/1/databases", success)
// by returning the promise that getJSON provides, we allow the caller to specify the promise handlers
return promise;
}
// Using callbacks
list(function(grades) {
console.log(grades);
});
// Using promises
list()
.success(function(grades) {
console.log(grades);
});
Why is the new Monsters object only being filled while being called inside the mysql function scope?
Monsters = {};
db.query('SELECT * from rpg_monsters ', function(err, results) {
for(i=0; i < results.length; i++){
Monsters[results[i].monster_id] = {
monster_id: results[i].monster_id,
monster_name: results[i].monster_name,
monster_filename: results[i].monster_filename,
monster_hp: results[i].monster_hp,
monster_chp: results[i].monster_hp,
monster_type: results[i].monster_type,
monster_level: results[i].monster_level,
xPosition: results[i].monster_xPosition,
yPosition: results[i].monster_yPosition
}
}
console.log(Monsters); // This Returns True with all the objects properties!
db.end();
});
console.log(Monsters); // This Returns Empty?
Is it possible use the Monsters object (or any) outside of the mysql callback?
Short answer: No.
Long answer: Welcome to asynchronous programming in NodeJS! Your error is not due to a scoping issue, but a time issue! Your asynchronous code does not run in source order. Your code does this:
initialize global variable Monsters reference an empty Javascript object
submit an asynchronous request to db.query, and pass a callback taking params err and results
console.log the contents of Monsters, which still references an empty array
NodeJS reaches the end of it's main loop and ticks. This may happen many times while waiting for db.query to finish its asynchronous IO. At some point in the future we resume:
db.query resolves and runs your callback function.
clone all elements in results into object at global variable Monsters
log value of Monsters
You will need to restructure your code to follow the asynchronous callback structure, or you can invesetigate alternatives like Promises or coroutines.
Please see How to return the response from an asynchronous call?, it has quite the explanation of your issue.
I have already started question about this on AngularJS, factory, do POST then GET method. I have to do POST request get json like {'exp':'2+3','token':'asd'}(SoluableNonagon answerd me very well), then get the token from json and to GET request like /something/:token, before that I'll have to check if token exist in json that i got with POST method. Can anyone tell me how can I do this and how can I call factory from controller that is doing post request?
every $http functions returns a promise, promises can be nested or serialized the return inside the function must be a promise in order to serialize your operations, the next then will be called when the $http.get is finally finished.
$http.post('post1').then(function (resultPost1) {
// do your stuff
return $http.get('get1');
}).then(function (resultGet1) {
// do your stuff
return $http.get('get2').then(function (resultGet2) {
// do your nested stuff
return $http.get('get3');
});
}).then(function (resultGet3) {
// do your stuff
});
More info on $q docs: https://github.com/kriskowal/q
I'm learning d3js. I came across an example for extracting CSV values here. I'm quoting the code:
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) { console.log(rows); });
From the description, I get that .row() is the accessor here. But the role of the .get() is not clear to me. When is this function called, and for what purpose ? Thanks.
The .get() is a function of the underlying AJAX request -- it sends the request and establishes the callback. From the documentation:
xhr.get([callback])
Issues this request using the GET method. If a callback is specified, it will be invoked asynchronously when the request is done or errors; the callback is invoked with two arguments: the error, if any, and the response value.