How to get info from a JSON? - javascript

I'm new around here and I'm studying JS! In particular JSON! However, I have come across an exercise that I cannot solve, also because I do not understand what I am doing wrong. I need to extract the information about the planets from the StarWars API. So I do the classic fetch and as a result I get the generic information about the planet in the form of a JSON.
However, I have to extract the planet name and I get stuck, because when I check the PlanetsData variable, it gives me undefined. Ergo the cycle I wrote to extract the names of the planets doesn't work for some reason.
So, my question is:
Why do I get "undefined" for the PlanetsData variable? .. Shouldn't I get the JSON, which displays correctly in the console?
Did I write the cycle correctly?
Thanks to who will answer me!
This is my code:
async function getPlanetsData() {
const planetsData = await fetch ("https://swapi.dev/api/planets").then(data => {
return data.json()}).then(planets => {console.log(planets.results)}) // ---> Here i receive the JSON data
for (let key in planetsData) {
const someInfo = planetsData.results[key].name
console.log(JSON.stringify(someInfo)) } // ---> I don't understand why, but I don't get anything here. There is no response in the console, as if the call did not exist
}
getPlanetsData()

You can write the same function in a different and clearer way,
check the comments to understand the code!
async function getPlanetsData() {
// 1. Fetch and wait for the response
const response = await fetch ("https://swapi.dev/api/planets");
// 2. Handle the response, in that case we return a JSON
// the variable planetsData now have the whole response
const planetsData = await response.json();
// console.log(planetsData); // this will print the whole object
// 3. Return the actual data to the callback
return planetsData;
}
// Function usage
// 4. Call "getPlantesData" function, when it completes we can call ".then()" handler with the "planetsData" that contains your information
getPlanetsData().then(planetsData => {
// 5. Do whatever you want with your JSON object
// in that case I choose to print every planet name
var results = planetsData.results; // result array of the object
results.forEach(result => console.log(result.name));
});

It seems that you have the same issue as : read and save file content into a global variable
Tell us if it does solve your issue or not.
(UPDATE)
To answer explicitly to your questions.
First question:
To get value into variable planetsData you can do this:
async function getPlanetsData() {
const response = await fetch ("https://swapi.dev/api/planets")
const planetsData = await response.json()
for (let key in planetsData) {
const someInfo = planetsData.results[key].name
console.log(JSON.stringify(someInfo))
}
}
getPlanetsData()
Second question:
You didn't write the cycle correctly.
To resolve promises it is preferable to choose between using await and.

Related

How to await asynchronous map function?

let me quickly get to the point. I have a function which fetches some user ids. It works very well.
const allIds = await fetchAllIds(someUrl);
Now the problem comes when I want to do something different. I'd like to loop over those ids and do some async await stuff with them. That is, to mainly fetch some data for each one with axios and modify them accordingly.
allIds.map(async (id) => {
// 1. Fetch some data (try, catch and await)
// 2. Modify the id based on that data
// 3. Return the id, namely replace the old one
});
At the end of my code, I simply return allIds. The problem is that it returns them without waiting for the map function to execute completely. I tried different methods and none of it seems to be working. Could you please help me to make it work or perhaps suggest some other possible solutions? Thanks in advance!
You basically have two problems:
You are ignoring the return value of the map
The map will return an array of Promises and you aren't awaiting them all
So:
const promises = allIds.map(...);
const replacement_ids = await Promise.all(promises);
return replacement_ids;
Use this instead.
const newList = await Promise.all(allIds.map(id=>new Promise(async(res)=>{
// do your async here and get result;
res(result);
})));

Why I get three undefined things and why there are two outputs in one call?

I'm new to react. So I'm developing a application which gets data from a api. So I used this piece of code to get data from a api.
let [jsonData,setJsonData]=useState([]);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(apiURL);
const json = await response.json();
setJsonData(json.components.map(function(item){
return item;
}))
} catch (error) { }
}
fetchData();
}, [])
const [table1,table2,pieChart]=jsonData;
console.log(table1,table2,pieChart)
This is the problem. When I run this I get a output like this.
In this why there are two outputs in the first call and in first output why I get 3 undefined things.I just need to get the only those JSON data in the first call.How do I get the required data only and not to get those undefined things.
Thanks in advance.
You can't avoid the fact that your fetch function is asynchronous, but you can do something like this:
if (!jsonData.length) return <div>loading...</div>;
You are doing an asynchronous request in your useEffect function, which means that your fetch function will run parallel to the current code but it will finish sometime after. So the first time you console.log those values the useEffect has not finished yet. At the end of your useEffect you used the setJsonData, which will make the component re-render with the updated state, hence this is why you see the second console.log with the correct values at last.

How to return a result properly from async/await function?

I have worked with async/await functions for a few months now and I have gotten all my code to work, however, I don't understand it completely and could use some words of wisdom.
In my code below I have an async function, my question is... why does it return a promise instead of the value I expect? And more importantly, what is the proper way to get the value I want?
getName = async () => {
const request = await fetch(apiUrl)
const data = await request.json()
return data.response.name
}
I call the function later
const name = getName()
But name is then a promise instead of the name.
I have looked this up many times and it never sticks. I am hoping using my own example if someone can explain it to me so I understand completely it will finally stick with me.
EDIT - In response to #Paulpro I have updated my question to below...
Assuming the async function is okay, the question is, how do I store the value.
const name = getName()
'name' is now a promise, so I normally do something like this...
getName().then(name => setName(name))
but how do I make const name === the returned name?
how do I make const name === the returned name?
By using const name = await getName().
Which means you have to use it inside an async function.
So your approach using:
getName().then(name => setName(name))
is most likely the best way to do it, but it really depends on the the rest of your code.
I mean you could do it like this:
let name;
getName = async () => {
const request = await fetch(apiUrl)
const data = await request.json()
name = data.response.name;
}
When (and if) both of your async requests finish, your name variable will have the result. But there is no guarantee on the timing of that. Depending on the app, it might be fine if you initialize your variable like this:
let name = 'Loading...';

Adonis Lucid ORM Not Returning data

I am new to Adonis JS so extremely sorry for the Stupid Question.
I have the default setup of Adonis JS with Mysql Database and everything working.
I have created a simple usertest route where I am returning JSON of user with ID: 1.
Below is the code for the same
Route.get('/usertest', ({ response }) => {
const User = use('App/Models/User')
let data = User.query().where('id', 1)
.first()
console.log(data)
return response.status(200).json(data)
})
But it is returning and empty object
Raw Response:
{}
Console Log Statement Response:
Promise { <pending> }
I am unable to understand what am I missing here.
Note: I tried let data = User.find(1) but it did not work.
Please help me.
Thanks in advance!!!
Quick note, at least you have to execute the query asynchronously.
I mean, you have to replace:
let data = User.query().where('id', 1)
.first()
by:
let data = await User.query().where('id', 1)
.first()
Of course, this mean you have to precede the function arrow with async:
Route.get('/usertest', async ({ response }) => {
// rest of the code
let data = await User.query().where('id', 1).first()
// rest of the code
})
It is very easy to miss "await" when you start working with async-await frameworks. Just a suggestion on the query whenever you want to find one object it is good practice to use ORM's predefined function. In this case
const user = await User.findBy('id',1)
this will return the first object it finds with the given id. You will find more options and help in knex.js docs http://knexjs.org/#Builder-where

Is it possible to group independent async functions under a single await?

Background
I am writing some asynchronous code in express. In one of my end points there I need to retrieve some data from firebase for 2 seperate things.
one posts some data
the other retrieves some data to be used in a calculation and another post.
These 2 steps are not dependent on one another but obviously the end result that should be returned is (just a success message to verify that everything was posted correctly).
Example code
await postData(request);
const data = await retrieveUnrelatedData(request);
const result = calculation(data);
await postCalculatedData(result);
In the code above postData will be holding up the other steps in the process even though the other steps (retrieveUnrelatedData & postCalculatedData) do not require the awaited result of postData.
Question
Is there a more efficient way to get the retrieveUnrelatedData to fire before the full postData promise is returned?
Yes, of course! The thing you need to know is that async/await are using Promises as their underlying technology. Bearing that in mind, here's how you do it:
const myWorkload = request => Promise.all([
postData(request),
calculateData(request)
])
const calculateData = async request => {
const data = await retrieveUnrelatedData(request);
const result = calculation(data);
return await postCalculatedData(result);
}
// Not asked for, but if you had a parent handler calling these it would look like:
const mainHandler = async (req, res) => {
const [postStatus, calculatedData] = await myWorkload(req)
// respond back with whatever?
}

Categories