【问题标题】:How to get the value in asyncfunction using node js?如何使用节点 js 获取 asyncfunction 中的值?
【发布时间】:2019-07-11 12:52:04
【问题描述】:

我尝试调用函数以将数据返回到异步函数中的 dict。但它不返回数据它返回异步函数如何在异步函数中获取数据可以给我任何解决方案。

.js 示例

function data()
{
    return "hai"
}

let dict = {sample:async () => {
    return (await data())
}}


console.log(await dict['sample'])

预期输出

hai

我得到了输出

[AsyncFunction: sample]

【问题讨论】:

  • 将您的 console.log(await dict['sample']) 更改为 console.log(await dict['sample']())

标签: node.js async-await node-modules


【解决方案1】:

在您的代码中,dict['sample'] 是一个异步函数。如果要从该函数中获取值,则必须调用该异步函数,然后该函数返回一个承诺。然后,您可以在该承诺上使用 .then()await 以从中获取价值。

而且,您的函数 data() 不是 async 函数,因此您不应在其上使用 await

将其分解为更多步骤以更好地理解它:

function data() {
    return "hai"
}

let dict = {
    sample: async () => {
        return data();
    }
};

let fn = dict['sample'];
fn().then(val => {
    console.log(val);
});  

或者,如果这一切都在 async 函数中,您可以使用 await 而不是 .then() 来获取值。所以,如果你想要一个单行:

console.log(await (dict['sample']()));

在任何一种情况下,async 函数总是返回一个 Promise(当您调用该函数时),从 Promise 中获取值的两种方法是使用 .then()await

【讨论】:

    【解决方案2】:

    必须是:

    onsole.log(await (dict['sample']()))
    

    否则你只是返回函数本身,而不是调用函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2023-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多