Sunday 18 December 2016

javascript - 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 connectionsWithEmails = await parseConnections('./tmp/connections.csv')
console.log(connectionsWithEmails)
return connectionsWithEmails
}

const connectionsWithEmailsHash = getConnectionsWithEmailsHash()
console.log(connectionsWithEmailsHash)


When I console.log() inside the async function, I get the hash I am expecting, but when I console.log() the result of calling the async function, I get promise pending. I though the point of an async function was that it waits for the promise to be resolved when it is called, so what I am I doing wrong?



Answer



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...
    })


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...