Search code examples
javascriptnode.jsasynchronousasync-awaites6-promise

What is the correct way to read a property of an object wrapped in a promise? (Getting TypeError)


I have a async function that fetches json from an API, and returns it, in Node.js. Essentially,

export async function getThing(URL){
  let res = await fetch(URL);
  let data = await res.json();
  return data;
}

This, as I understand it, should return a promise. Within the calling function, I assign this to a variable, then assign other variables to its properties, and build an object out of them.

async function dostuff(){
  let inner = await exportedfile.getThing(URL);
  let gamedescription = inner.propertyOfInner;
}

This seems to work successfully, the objects being built with the right fields. However, at the same time, it throws errors for each time I do this, reading

Uncaught (in promise) TypeError: Cannot read property 'propertyOfInner' of undefined

Even though it clearly is reading that property successfully. So while the fields are being correctly populated when the promises resolve, clearly I'm doing something wrong. What is the correct way to read a property of an object wrapped in a promise?


Solution

  • Uncaught (in promise) TypeError: Cannot read property 'propertyOfInner' of undefined

    Above error means that you cannot access 'propertyOfInner' from undefined, This means somehow your 'inner' variable is undefined at some point.

    I suggests you to access property as follows

    if (inner) {let gamedescription = inner.propertyOfInner;}