【问题标题】:Why is my async function returning too soon? [duplicate]为什么我的异步函数返回得太快了? [复制]
【发布时间】:2019-02-26 08:02:34
【问题描述】:

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

const getConnectionsWithEmailsHash = async () => {
    const connectionsWithEmails = await parseConnections('./tmp/connections.csv') 
    console.log(connectionsWithEmails)
    return connectionsWithEmails
}

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

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

【问题讨论】:

  • 你忘了等待它。你不能像那样跳出异步逻辑
  • 我在函数中等待它。我认为 await 只能在异步函数中使用?
  • 没错,你不能在异步函数之外使用 await。您也无法返回或访问尚不存在的值。

标签: javascript node.js async-await


【解决方案1】:

getConnectionsWithEmailsHash 本身仍然是一个异步函数。 connectionsWithEmails 有效,因为您等待 parseConnections,但 connectionsWithEmailsHash 无效,因为 getConnectionsWithEmailsHash 并行运行。尝试“等待 getConnectionsWithEmailsHash”。

现在,如果您想在顶层使用它,那是另一个问题。该问题已回答here

【讨论】:

  • 那么我将不得不将它包装在另一个异步函数中?我认为 await 只能在异步函数中调用?
  • 好吧,从逻辑上讲,如果你这样做了,那么你就会冻结主线程。 JS 出于理智的原因阻止了这种情况,但了解 JS 为何这样做是有益的。即使语言允许,您也不希望顶级等待。
  • @adamtropp 最终,您需要以某种方式解决来自最高异步功能的承诺 - 例如通过 try/catch 或 then/catch 块。
【解决方案2】:

async 函数返回承诺。这一行:

const connectionsWithEmailsHash = getConnectionsWithEmailsHash()

...只是将connectionsWithEmailsHash 设置为函数返回的承诺。要真正获得 Promise 的分辨率值,您需要:

  1. 在另一个 async 函数中使用 await(如果这意味着在顶层使用 async,请参阅:How can I use async/await at the top level?):

    const connectionsWithEmailsHash = await getConnectionsWithEmailsHash()
    

    或者,

  2. 在承诺上使用then

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

【讨论】:

    【解决方案3】:

    我认为您不需要包装函数。 const connectionWithEmailHash = await parseConnections(arg);

    这应该适用于给定的代码。

    有问题的代码 sn-p 将不起作用,因为异步函数应该返回一个承诺。因此,请尝试在 getConnectionWithEmailHash 中返回一个使用connectionsWithEmails 解析的promise,您的代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2021-12-19
      • 1970-01-01
      • 2021-05-08
      • 2020-08-30
      • 2020-08-26
      • 2020-06-13
      相关资源
      最近更新 更多