簡體   English   中英

為什么我的函數返回 [AsyncFunction: repo]?

[英]Why does my function return [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() 問題是,我不想將我的應用程序的所有代碼都放在.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)
})()

異步函數始終返回 promise 對象,因此您可以使用 promise.then() 訪問結果,例如

repo.repo().then(result => result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM