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:
Use
await
within anotherasync
function (if that means usingasync
at the top level, see: How can I use async/await at the top level?):const connectionsWithEmailsHash = await getConnectionsWithEmailsHash()
or,
Use
then
on the promisegetConnectionsWithEmailsHash()
.then(connectionsWithEmailsHash => {
// ...use `connectionsWithEmailsHash`....
})
.catch(error => {
// ...handle error...
})
No comments:
Post a Comment