javascript - 为什么我的函数返回 [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
任何地方。
解决方案
每个 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)
})()
推荐阅读
- java - 用两个循环和两个输出语句重写代码
- python - 如何保存然后从数据框中的文件名中提取一些信息
- java - 在 JDBC 连接上设置时区
- java - 我的项目中的错误
- python-3.x - 如何使用 Python 和 Selenium 处理摘要身份验证
- python - 如何检查一个单词是否按字母顺序出现在python中另一个单词之前或之后?
- javascript - 如何在js中找到画布的中心
- floating-point - 32 位浮点数可以精确表示到小数点后的最高值是多少?
- ios - iOS 上的 Firebase 云消息传递
- typescript - 打字稿 - 接口中的默认函数 - > 错误(TS)属性或预期签名