Node.js中如何通过回调从函数获取JSON数据到变量?
Hey there! I see you're trying to grab specific fields like displayName from the StarCraft 2 profile data using the battlenet-api, but running into issues with direct variable assignment. Let's break down why this happens and how to fix it.
Why Direct Assignment Doesn't Work
The sc2.profile.profile() function is asynchronous — it doesn't return the profile data immediately when you call it. Instead, it relies on a callback function to pass you the data once the API request completes successfully (or an error if something goes wrong). When you try var profileInfo = sc2.profile.profile(...), you're just capturing the function's immediate return value (which is probably undefined), not the actual profile data.
Solution 1: Use the Callback Function Directly
The simplest way to extract your desired fields is to handle the data inside the provided callback. Here's how you can do it:
// Call the profile function with your parameters and a callback sc2.profile.profile( { id: profileId, region: profileRegion, name: profileName }, function(error, profileData) { // First, check if there was an error with the request if (error) { console.error('Failed to fetch profile:', error); return; } // Extract the displayName field from the returned JSON const displayName = profileData.displayName; // Now you can use displayName for whatever you need console.log("Player's Display Name:", displayName); doSomethingWithDisplayName(displayName); // Example: pass to another function } );
Solution 2: Wrap It in a Promise for Async/Await (Cleaner Syntax)
If you prefer working with modern async/await syntax instead of callbacks, you can wrap the function in a Promise. This makes your code look more synchronous and easier to read:
// Create a helper function that returns a Promise function fetchSc2Profile(profileId, profileRegion, profileName) { return new Promise((resolve, reject) => { sc2.profile.profile( { id: profileId, region: profileRegion, name: profileName }, (error, data) => { if (error) { reject(error); // Pass the error to the catch block } else { resolve(data); // Pass the profile data to the then block/await } } ); }); } // Use async/await to fetch and process the profile async function processSc2Profile() { try { const profileData = await fetchSc2Profile(profileId, profileRegion, profileName); const displayName = profileData.displayName; // Do your work with displayName here console.log("Extracted Display Name:", displayName); } catch (error) { console.error('Error fetching profile:', error); } } // Call the async function to start the process processSc2Profile();
The key takeaway here is that asynchronous operations like API calls don't return data right away — you have to wait for the operation to finish using either callbacks or Promises/async-await to access the actual response data.
内容的提问来源于stack exchange,提问作者spikegd

