为什么我的异步函数返回得太早? [英] Why is my async function returning too soon?

查看:49
本文介绍了为什么我的异步函数返回得太早?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用异步函数在另一个函数中调用一个函数.看起来像这样:

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) 

当我在async函数中使用console.log()时,会得到期望的哈希值,但是当我在console.log()中调用异步函数的结果时,我将得到未决的承诺.尽管异步函数的要点是,它会在调用时等待promise解析,所以我做错了什么?

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?

推荐答案

async 函数返回promise.这行:

async functions return promises. This line:

const connectionsWithEmailsHash = getConnectionsWithEmailsHash()

...只需将 connectionsWithEmailsHash 设置为函数返回的承诺即可.要真正获得承诺的解决方案价值,您需要:

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

  1. 在另一个 async 函数中使用 await (如果这意味着在顶层使用 async ,请参见:

  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()

对诺言使用 then

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

这篇关于为什么我的异步函数返回得太早?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆