如何在异步函数中获取价值?

时间:2019-05-09 04:11:26

标签: node.js nodejs-stream nodejs-server

我在节点js中尝试了两个函数(异步函数,普通函数)。普通函数成功返回值,但是异步函数无法返回值。如何修复

正常功能

index.js

var sample_data = require('./product')

const data = sample_data
console.log(data)

product.js

function sample()
{
    console.log("hai")
    return "hello"
}

module.exports = sample

异步功能

index.js

var sample_data = require('./product')

const data = sample_data
console.log(data)

product.js

async function sample()
{
    console.log("hai")
    return "hello"
}

module.exports = sample

正常功能

预期输出
hai
你好

异步功能

预期产量
hai
你好

但是我得到了输出
[AsyncFunction:示例]

2 个答案:

答案 0 :(得分:1)

有两种方法

使用then

sample().then(result => console.log(result));

使用await等待或获得结果,直到执行下一条语句为止

var result = await sample();
console.log(result);

答案 1 :(得分:0)

异步函数将返回值包装在promise中,以便查看所需的结果。then()

   sample().then(result=>{console.lot(result)});