-2

I'm using an async function that awaits a GraphQL call. The GraphQL call returns a Promise that does contain the data I want. However, I'm unable to figure out a way to access it.

Here is the code:


export async function getModel() {
    try {
        const router = useRouter()
        const {id} = router.query
        console.log("id="+id)
        const res = await API.graphql({
            query: queries.getYawaraModel,
            variables: {id: id}
        })

        return (
            res
        )
    } catch (e) {
        console.log("my error:"+e)
    }
}

export default function Detail({props}) {
    const technique = getModel()
    console.log('technique', technique)
    return <TechniqueListCard
        Description={technique?.Description}
        Technique={technique?.Name}
    />;
}

Here is a snapshot of the console log proving the payload data has been returned:
enter image description here

How do I access the contents of the returned Promise?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Tennis Smith
  • 451
  • 6
  • 14
  • Canonical: https://stackoverflow.com/q/29516390/3001761, https://stackoverflow.com/q/14220321/3001761 – jonrsharpe Apr 24 '23 at 22:57
  • @jonrsharpe Those are similar, but not the same. There isn't an explicit call to a Promise in the example code. The question is how would that be introduced? – Tennis Smith Apr 24 '23 at 23:02
  • 2
    What do you mean _"an explicit call to a Promise"_ - what do you think `API.graphql` returns, and if _not_ a promise why do you `await` it? And `async` functions **always** return promises, so what's `getModel()` if not an explicit call to a promise? Yes, it's the same. – jonrsharpe Apr 24 '23 at 23:04
  • @jonrsharpe OK. So a promise is returned on an async call. Got it. Then how is the promise used to access the payload information. What's the construct? – Tennis Smith Apr 24 '23 at 23:10
  • `const technique = await getModel()`, but in an async function. – jarmod Apr 24 '23 at 23:22

1 Answers1

-1

You need to await the getModel function.

export default async function Detail({props}) {
    const technique = await getModel()
    console.log('technique', technique)
    return <TechniqueListCard
        Description={technique?.Description}
        Technique={technique?.Name}
    />;
}
Deborah
  • 9
  • 1
  • 3