Reputation: 478
I am trying to do some dynamic data modeling with async/await. I have two endpoints the first will return an array of objects. These entities in the array have children which are to get from another endpoint.
So the result I'm trying to achieve is similiar to:
[{
root: {
id: 'root1'
},
children: [
{
id: 'child1'
},
{
id: 'child2'
},
]
}]
This is how I try to solve this:
let data = await rootLevel();
let levelOneData = [];
levelOneData = data.map((e) => {
let rootNode = {};
rootNode["root"] = e;
return rootNode;
});
let levelTwoData = await Promise.all(
levelOneData.map(async (e) => {
let response = await fetch(
`APIURL{e.parent.ID}`
);
let responseJSON = response.json();
e["children"] = responseJSON;
return e;
})
);
const rootLevel = async () => {
let response = await fetch(
`APIURL`
);
return response.json();
};
What I am expecting:
children: {Array(26)}
What I am getting:
children: Promise {<resolved>: Array(26)}
I am somehow overtseeing something in my Promise.all chain, so I am only getting resolved Promises in my data object, any tips on how to get plain data in there? Or how to mutate an array of resolved promises to actual data?
Upvotes: 0
Views: 48
Reputation: 707158
Change this:
let responseJSON = response.json();
to this:
let responseJSON = await response.json();
response.json()
is asynchronous and returns a promise. You were just putting that promise in your result without ever waiting for it.
Upvotes: 2