首页 > 解决方案 > 为什么我的函数返回 [AsyncFunction: repo]?

问题描述

我正在尝试使用 async/await 功能来构建节点 JS 脚本。我目前有一个称为repo.js帮助文件的文件,用于从 Github 的 API 获取数据并将其返回给一个变量,以便我在我的节点应用程序的不同 JS 文件中的其他地方访问,repo.js如下所示:

const axios = require('axios')

const repo = async () => {
  const data = await axios.get('https://api.github.com/repos/OWNER/REPO/releases', {
    headers: {
      'Authorization': 'token MYTOKEN'
    }
  })
  return data
}

exports.repo = repo

然后在我的main.js文件中我正在尝试做......

const repo = require('./src/utils/repo')

program
  .option('-d, --debug', 'output extra debugging')
  .option('-s, --small', 'small pizza size')
  .option('-p, --pizza-type <type>', 'flavour of pizza')

const repoData = repo.repo
console.log(repoData)

不幸的是,这只是返回[AsyncFunction: repo]到控制台,这不是预期的行为。为什么我不能访问这里的内容?

更新

根据我收到的一些回复,我知道我需要在异步函数中使用我的代码或使用.then(). 问题是,我不想将我的所有应用程序代码都放在 a 中,.then()只是为了依赖 API 中的一件事。

例子:

var version = ''
repo.getRepoDetails().then((res) => {
  version = res.data[0].body.tag_name
})

现在我可以访问version任何地方。

标签: javascriptnode.jsasync-awaitaxiosgithub-api

解决方案


每个 async/await 函数都是一个 Promise,这意味着您需要等待它完成才能读取它的结果。

repo.repo().then(res => console.log(res))

如果您的应用程序是一个简单的 nodejs 脚本(或单个文件),那么您可以将代码包装在IIFE 中,如下所示:

const repo = require('./src/utils/repo')

(async () => {
  program
    .option('-d, --debug', 'output extra debugging')
    .option('-s, --small', 'small pizza size')
    .option('-p, --pizza-type <type>', 'flavour of pizza')

  const repoData = await repo.repo() <--- You can use await now instead of then()
  console.log(repoData)
})()

推荐阅读