You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

How to Fetch Twitch User Data with Promises (and Fix Your 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:

  1. You weren't returning the Promise from your fetch function
    If your function that calls fetch doesn't return the fetch Promise (or any Promise), there's nothing to attach a then to. In the example above, getTwitchUser explicitly returns the result of fetch(...)—that's non-negotiable for chaining then.

  2. You weren't using Promise.all for multiple requests
    If you were looping through usernames and calling fetch one by one without collecting those Promises into an array, you might have been trying to attach then to a regular loop (not a Promise). Promise.all takes an array of Promises and returns a single Promise that resolves only when all of them are done—perfect for your use case.

  3. Uncaught errors were stopping execution
    If any of your fetch requests 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 like then never ran. Always add .catch() to catch these issues.

  4. You forgot to parse the JSON response
    fetch resolves with a Response object, not the actual JSON data. You need to call response.json() (which returns another Promise) and return that in your then to pass the parsed data along. Skip this step, and your next then won'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). fetch returns 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, not undefined. If it's undefined, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:53:56