Skip to content Skip to sidebar Skip to footer

Why Is My Async Function Returning Too Soon?

I am trying to use an async function to call a function inside another function. It looks like this: const getConnectionsWithEmailsHash = async () => { const connectionsWit

Solution 1:

async functions return promises. This line:

const connectionsWithEmailsHash = getConnectionsWithEmailsHash()

...just sets connectionsWithEmailsHash to the promise that the function returns. To actually get the resolution value of the promise, you'd need to:

  1. Use await within another async function (if that means using async at the top level, see: How can I use async/await at the top level?):

    const connectionsWithEmailsHash = await getConnectionsWithEmailsHash()
    

    or,

  2. Use then on the promise

    getConnectionsWithEmailsHash()
    .then(connectionsWithEmailsHash => {
        // ...use `connectionsWithEmailsHash`....
    })
    .catch(error => {
        // ...handle error...
    })
    

Solution 2:

getConnectionsWithEmailsHash is still an async function itself. connectionsWithEmails is valid because you awaited parseConnections, but connectionsWithEmailsHash is not valid because getConnectionsWithEmailsHash is running in parallel. Try "await getConnectionsWithEmailsHash".

Now, if you want to use this on the top level, that's another question. That question is answered here.

Solution 3:

I think you don't need a wrapper function. const connectionWithEmailHash = await parseConnections(arg);

This should work for given code in question.

Code snippet in question won't work since async function should return a promise. So try returning a promise in getConnectionWithEmailHash that resolves with connectionsWithEmails and your code should work.

Post a Comment for "Why Is My Async Function Returning Too Soon?"