0

I call a function then output it's return value in console, like so:

Index.getInitialProps = async ctx => {
    const { loggedInUser } = await checkLoggedIn(ctx)
    console.log('Data actually returned:')
    console.log(loggedInUser)
    return { loggedInUser }
}

Pretty straight forward...

The checkLoggedIn function is as follows:

export function checkLoggedIn(ctx) {
    ctx.apolloClient.query({
        query: GET_ME,
    })
        .then(({ data }) => {
            console.log('Data to be returned:')
            console.log(data)
            return { loggedInUser: data }
        })
        .catch(() => { return { loggedInUser: {} } })
}

Again, pretty straight forward. This is essentially an exact copy of this example: checkLoggedIn() and getInitialProps

Now what I would expect to happen is that I should see the following in the console:

Data to be returned:
{ <DATA> }
Data actually returned:
{ loggedInUser: { <DATA> }

Instead, I see:

Data actually returned:
undefined
Data to be returned:
{ <DATA> }

Which makes zero sense as the function is returning the correct data, and it should await for this returned data before proceeding to the console.log.

Instead, it completely ignores the 'await' and doesn't even bother waiting for the function to return a value before continuing.

What is going on here?

Jake
  • 3,865
  • 5
  • 25
  • 58

3 Answers3

3

You can only (usefully) await a promise.

The function checkLoggedIn has no return statement, so it returns undefined.

undefined is not a promise, so awaiting it has no effect.

Change checkLoggedIn so it returns the promise.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • You can `await` a non-promise. `await 43` evaluates to `43`. It just doesn't make much sense to do it. – Amadan Mar 25 '19 at 09:39
  • It has return in both the .then() and .catch() though, so no matter what it should return a value? – Jake Mar 25 '19 at 09:40
  • See my answer. It returns from the anonymous callback function, not from `checkLoggedIn`. – Amadan Mar 25 '19 at 09:41
  • @GCM — No. That isn't how returning a value from a callback works. If you want to return from `checkLoggedIn`, then `checkLoggedIn` itself needs a `return` statement. – Quentin Mar 25 '19 at 09:41
3

() => { return { loggedInUser: {} } } is a function that returns { loggedInUser: {} }. Ditto for the function inside then.

Thus, checkLoggedIn has no return. It should return the promise it constructs:

return ctx.apolloClient.query({
Amadan
  • 191,408
  • 23
  • 240
  • 301
-2

I think you should make checkLoggedIn an async function

orhan fidan
  • 126
  • 3
  • 12
  • Then its return value becomes a promise that resolves immediately as `undefined` which isn't helpful. – Quentin Mar 25 '19 at 09:40