JavaScript中Destiny2 API调用的then函数未执行问题
Troubleshooting Your Destiny2 Client
getProfile then Callback Issue Let’s break down what’s going wrong with your second client.getProfile call, plus some key fixes to make your code work reliably:
The Core Problem: Unused Arrow Functions in Your then Callback
Take a look at your second getProfile invocation:
client.getProfile(name, '4').then( function(value) { data => pId.appendChild(document.createTextNode("Platform:" + data.profile.platform[1])); data => pName.appendChild(document.createTextNode("Name:" + data.profile.displayName)); } );
You’ve defined two arrow functions inside the then callback, but you never actually execute them. These are just function definitions sitting idle—they won’t run unless you call them. On top of that, you’re ignoring the value parameter passed to the then callback, which is the actual resolved data from the API Promise.
Fixed Code Example
Let’s rewrite this to fix the callback issue, plus eliminate redundant API calls and add error handling:
const { Client } = require('destiny2'); const client = new Client('apiKey'); window.memberName = function(){ const pName = document.getElementById('memberName'); const pId = document.getElementById('memberId'); const name = document.getElementById('search').value; // Use a single API call instead of two duplicate requests client.getProfile(name, '4') .then(data => { console.log(data); // Keep your logging from the first call // Update DOM elements directly with the resolved API data pId.appendChild(document.createTextNode("Platform:" + data.profile.platform[1])); pName.appendChild(document.createTextNode("Name:" + data.profile.displayName)); }) .catch(error => { // Critical: Catch failed requests to debug issues console.error("Profile fetch failed:", error); alert("Could not load profile data. Check your input or API key."); }); }
Key Improvements Explained
- No duplicate API requests: Instead of calling
getProfiletwice (which sends two separate calls to the Destiny 2 API), we reuse one Promise and handle both logging and DOM updates in a singlethencallback. - Properly use resolved data: The
dataparameter in thethencallback is the actual API response—we use it directly to update your DOM elements, no unnecessary nested functions needed. - Error handling: Adding a
catchblock is essential. If your API request fails (invalid key, wrong username, network issue), thethencallback won’t run—catchlets you debug the problem and notify the user.
Additional Checks to Ensure Success
- Double-check that your API key is valid and has permissions for the
getProfileendpoint. - Confirm the
namevariable is correctly capturing input from yoursearchelement (log it to the console to verify). - Use your browser’s developer console (F12) to check for network errors or JavaScript exceptions—this will often reveal exactly why the Promise didn’t resolve as expected.
内容的提问来源于stack exchange,提问作者AOD Saenai
相关产品推荐
相关产品推荐

