GitHub API获取的JSON对象控制台可见但代码中无法使用问题咨询
Hey Liam, let's break down what's going on here—this is a super common pitfall with asynchronous API calls!
The Root Cause: Asynchronous Timing
When you call getGPD() with the GitHub API URL, you're making an HTTP request, which is asynchronous. That means your code doesn't wait for the API to send back data before moving on.
- When you assign
var GPD = getGPD(...),GPDis almost certainly aPromiseobject (not the actual JSON data) at the moment your code tries to use it. - The console shows the JSON data because browsers use "lazy evaluation" for logged objects—they update the display once the Promise resolves and the data is available, even though the variable was a Promise when you first logged it.
- Your local JSON object works because it's synchronous—the data is immediately available when you assign it.
Fixes to Try
1. Use async/await (Modern Approach)
If getGPD() returns a Promise (which it should if it's using fetch or a Promise-based HTTP client), rewrite your function to wait for the data to arrive:
async function drawProjects() { // Wait for the API request to finish before assigning GPD var GPD = await getGPD('https://api.github.com/repos/frc5104/Power-Up-2018/projects'); console.log(GPD); // Now you can use GPD normally here—e.g., GPD[0].name to get the first project's name }
Just make sure you call drawProjects() correctly (if you're calling it from another function, that function might also need to be async, or you can use .then()).
2. Use Callback Functions (If getGPD Uses Them)
If getGPD() is built with traditional callbacks (takes a success handler as a second argument), move your data-handling logic inside the callback:
function drawProjects() { getGPD('https://api.github.com/repos/frc5104/Power-Up-2018/projects', function(GPD) { console.log(GPD); // All code that uses GPD needs to live inside this callback }); }
3. Verify getGPD Parses the JSON
Double-check that getGPD() is actually converting the API's JSON response into a JavaScript object. If it's returning raw text, parse it manually:
async function drawProjects() { var rawResponse = await getGPD('https://api.github.com/repos/frc5104/Power-Up-2018/projects'); var GPD = JSON.parse(rawResponse); console.log(GPD); // Now GPD is a usable object }
Quick Test to Confirm
Add console.log(typeof GPD, GPD instanceof Promise); right after assigning GPD in your original code. If it logs object true, you know you're dealing with a Promise—and need one of the fixes above.
内容的提问来源于stack exchange,提问作者LiamSnow

