从异步/等待函数返回值

时间:2019-12-25 05:38:49

标签: javascript asynchronous

下面的模板是Template类的对象- 我正在尝试从异步函数返回模板对象,并且从我看到的内容中可以看到,但是没有。如果我将console.log语句放在该函数中,则它可以工作,但无法从runDir()函数返回模板对象。

下面的函数为什么不返回可在console.log语句中使用的模板对象。

async function runDir() {

const template = await Template.fromDirectory('./src/acceptance-of-delivery');

return template;

};

template = runDir();

console.log("Name: " + template.getName())
console.log("From Directory Template Version: " + template.getMetadata().getVersion())
console.log("Description: " + template.getDescription())
console.log("Hash: " + template.getHash())

2 个答案:

答案 0 :(得分:0)

您需要等待rundir的执行完成,以便初始化模板。 异步功能默认会返回一个Promise。

async function runDir() {

const template = await Template.fromDirectory('./src/acceptance-of-delivery');

return template;

};

template = await runDir();
// You need to wait for the execution of rundir to complete , so that template gets initialized
console.log("Name: " + template.getName())
console.log("From Directory Template Version: " + template.getMetadata().getVersion())
console.log("Description: " + template.getDescription())
console.log("Hash: " + template.getHash())

答案 1 :(得分:0)

runDir是一个异步函数,其返回值将为Promise。因此,template实际上是Promise。试试这个

runDir().then(template => {
  console.log("Name: " + template.getName())
  console.log("From Directory Template Version: " + template.getMetadata().getVersion())
  console.log("Description: " + template.getDescription())
  console.log("Hash: " + template.getHash())
})