You are missing two return statements to actually pass the values from one promise to the next. So to make your code work, you have to include them:
async function getData(){
const url = "https://jsonplaceholder.typicode.com/users";
url2='https://jsonplaceholder.typicode.com/posts/'
const data = await fetch(url).then((res) =>{
return res.json().then((dataAsJson) => {
return(dataAsJson[0].id);
})
.then((id)=>{
return fetch(url2+"/"+id).then((res)=> {
return res.json().then((data) => {
return(data);
})
})
})
})
}
One more tip here: When returning from a promise, it doesn't matter if it is another promise or a simple value - the next then
call will always get the unwrapped value. So you actually don't have to nest all those promise calls. It would be way more readble if you put it like this:
const url = "https://jsonplaceholder.typicode.com/users";
url2='https://jsonplaceholder.typicode.com/posts/'
const data = await fetch(url)
.then((res) =>{ return res.json()})
.then((dataAsJson) => { return(dataAsJson[0].id); })
.then((id)=>{ return fetch(url2+"/"+id); })
.then((res)=> { return res.json(); })
And also: Since you are just returning one value in each callback, you can make use of the JavaScript-Arrow-Function functionality that automatically returns if there is only one expression and short it even more to this:
const url = 'https://jsonplaceholder.typicode.com/users';
url2 = 'https://jsonplaceholder.typicode.com/posts/';
const data = await fetch(url)
.then(res => res.json())
.then(dataAsJson => dataAsJson[0].id)
.then(id => fetch(`${url2}/${id}`))
.then(res => res.json());
That is better readable and errors are easier to spot. :)
Update: I totally overlooked that in your code, your are trying to read synchronsouly from the asynchronous getData()
function. @the spectre cleared that up in his answer - so this should be the accepted one. However, to not let a wrong code stand, I edited the correct behaviour into my answer.