JavaScript Promise使用问题:脚本未执行then方法及Twitch API批量请求
Hey there! Let's get your Twitch API script working with Promises properly—since you're new to them, I'll walk through this step by step, including fixing that pesky then issue you're facing.
then Problem) First, let's start with a complete, working example. This script will fetch data for multiple usernames, collect all the results into an array, and use then exactly how you need:
// Your list of target usernames const targetUsernames = ["twitch", "shroud", "pokimane"]; // Helper function to fetch a single user's data from Twitch API function getTwitchUser(username) { const apiUrl = `https://api.twitch.tv/helix/users?login=${username}`; // Critical: Return the fetch Promise directly! return fetch(apiUrl, { headers: { // Replace these with your actual Twitch credentials "Client-ID": "YOUR_CLIENT_ID", "Authorization": "Bearer YOUR_OAUTH_TOKEN" } }) .then(response => { // First, check if the request succeeded if (!response.ok) { throw new Error(`Failed to fetch ${username}: ${response.statusText}`); } // Parse the JSON response (this returns another Promise) return response.json(); }); } // Use Promise.all to handle all requests at once Promise.all(targetUsernames.map(username => getTwitchUser(username))) .then(allUserData => { // allUserData is an array of the JSON responses for each user console.log("All user data collected:", allUserData); // Now you can use this array for your后续 operations }) .catch(error => { // Always handle errors—this will catch any failed requests console.error("Something went wrong:", error); });
Why Your then Wasn't Running
Let's break down the most common mistakes that would prevent your then handler from executing:
You weren't returning the Promise from your fetch function
If your function that callsfetchdoesn't return thefetchPromise (or any Promise), there's nothing to attach athento. In the example above,getTwitchUserexplicitly returns the result offetch(...)—that's non-negotiable for chainingthen.You weren't using
Promise.allfor multiple requests
If you were looping through usernames and callingfetchone by one without collecting those Promises into an array, you might have been trying to attachthento a regular loop (not a Promise).Promise.alltakes an array of Promises and returns a single Promise that resolves only when all of them are done—perfect for your use case.Uncaught errors were stopping execution
If any of yourfetchrequests failed (bad credentials, network issues, Twitch returning an error), and you didn't have a.catch()handler, the error might have silently crashed your script (depending on your environment), making it look likethennever ran. Always add.catch()to catch these issues.You forgot to parse the JSON response
fetchresolves with aResponseobject, not the actual JSON data. You need to callresponse.json()(which returns another Promise) and return that in yourthento pass the parsed data along. Skip this step, and your nextthenwon't get the data you expect.
Quick Promise Basics to Lock In
Since you're new to Promises, here's the core stuff you need for this script:
- A Promise represents an asynchronous operation (like a network request).
fetchreturns one automatically. .then()runs only when the Promise successfully resolves—you can chain these to process results..catch()runs if the Promise rejects (an error occurred)—always use this to avoid silent failures.Promise.all()lets you handle multiple Promises at once, waiting for all to finish before moving to the next step.
Troubleshooting Next Steps
If you're still stuck, try these quick checks:
- Log the result of your fetch function:
console.log(getTwitchUser("test-username"))should show a Promise object, notundefined. If it'sundefined, you're not returning the Promise. - Open your browser's DevTools Network tab: Check if your requests are actually hitting the Twitch API, if they're returning a 200 status, and if the response has the data you expect.
- Double-check your Twitch credentials: The API requires a valid Client ID and OAuth token now—missing or invalid ones will cause failed requests.
内容的提问来源于stack exchange,提问作者Cdhippen

