【问题标题】:Trouble making a list of commits with axios.get()使用 axios.get() 制作提交列表时遇到问题
【发布时间】:2019-11-20 21:49:33
【问题描述】:

我正在尝试使用 Github API 检索存储库中的提交列表。检索此列表后,我想将其分配给我定义的列表变量。

我想要这样做的原因是我可以提取有关拉取请求、提交关联的文件以及从文件中添加/删除的行数的信息。到目前为止,我有以下代码:

var listOfCommits = [];
const axios = require('axios');

axios.get(githubAPI).then(function (response) {
    listOfCommits = response['data'];
    console.log("in then part");
    console.log(listOfCommits[0]);
}).catch(function (error) {
    console.log("Error: something wrong happened");
}).finally(function () {
    console.log("hopefully this is done right...");
});

console.log("outside of the axios method");
console.log(listOfCommits[0]);
console.log("last debug");

我正在使用 Webstorm,所以当我使用“node file.js”运行文件时,我得到以下输出:

在 axios 方法之外
未定义
上次调试
在接下来的部分
[从存储库中检索到的东西]
希望这是正确的......

变量githubAPI 是一个字符串,用于存储API 检索必要信息所需的URL。此代码的目标是将检索到的信息分配给变量listOfCommits。在axios.get() 方法中,定义了listOfCommits,但是当我尝试在该方法之后再次打印出来时,它是undefined

我知道这与axios.get() 返回一个承诺有关,但我不知道如何解决这个问题,因为我对 Javascript 不太熟悉。任何帮助将非常感激。谢谢!

【问题讨论】:

  • 你变得不确定是有道理的。你是从 Promise 之外调用数据,你不能保证数据会在那个时候准备好。
  • 我知道。但我的问题是,有什么方法可以确保 listOfCommits 的数据超出了承诺范围,以便我可以使用它?还是我必须在承诺范围内做所有事情,比如获得拉取号码和我想做的所有其他事情?

标签: javascript git asynchronous promise axios


【解决方案1】:
let listOfCommits = null;
(() => {
  return new Promise((resolve, reject) => {
    axios.get('')
    .then((resp) => {
        resolve(resp['data']);
      },
      error => {
        reject(error);
      }
    );
})
})()
.then((data)=> {
  listOfCommits = data;      
})

【讨论】:

  • 我必须在 .then((data)=> { listOfCommits = data; 之后使用 listOfCommits 吗?因为我试过这个,如果我放了一个打印语句 console.log(listOfCommits[0]);在整个函数之外,它仍然说它是未定义的!
  • 您应该问问自己,该 listOfCommits 会发生什么...您可能需要为您的应用程序考虑一种“更具反应性”的方法。
  • 问题是 axios 调用将在另一个线程中执行,并且在点击控制台语句之前不会完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多