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

Promise.then()打印有数据但返回值为undefined及令牌刷新函数问题

Hey there! Let's work through your two Promise headaches—they're super common when you're getting the hang of async JavaScript, so don't stress too much. I'll break each one down with examples to make it clear.

1. Why does .then() log data but returning the value gives undefined?

This almost always boils down to not returning the Promise chain or the data within .then(). Remember: Promises are asynchronous, so if your outer function doesn't return the entire Promise sequence, or you forget to pass the data along in .then(), the caller will get undefined because the async operation hasn't finished yet.

Example of the mistake:

function fetchUser() {
  // Oops—no return here, so the function doesn't pass along the Promise
  fetch('/api/user')
    .then(res => res.json())
    .then(user => {
      console.log(user); // This works because we're inside the .then() callback
      // Forgot to return user here, so the next step in the chain gets nothing
    });
}

const userData = fetchUser();
console.log(userData); // Logs undefined immediately—async operation isn't done!

Fix it by returning the chain and data:

function fetchUser() {
  // Return the entire Promise chain so callers can wait for it
  return fetch('/api/user')
    .then(res => res.json())
    .then(user => {
      console.log(user);
      return user; // Pass the user data to the next .then() or caller
    });
}

// Now you can wait for the Promise to resolve
fetchUser().then(user => {
  console.log(user); // Logs the actual user data
});

// Or use async/await for cleaner code
async function getUser() {
  const user = await fetchUser();
  console.log(user);
}

2. Why does refreshAccessToken() return undefined first, then the real data?

Same root issue: async operations don't block execution. If you call refreshAccessToken() without waiting for its Promise to resolve, you'll get undefined right away because the network request is still in flight. You need to make sure you wait for the Promise to finish before using the new access token.

First, double-check that refreshAccessToken() actually returns a Promise (it should!):

function refreshAccessToken() {
  // Return the fetch Promise so callers can await it
  return fetch('/api/refresh-token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refreshToken: localStorage.getItem('refreshToken') })
  })
  .then(res => res.json())
  .then(response => {
    // Save the new access token somewhere (like localStorage)
    localStorage.setItem('accessToken', response.accessToken);
    // Return the token so it's available to the caller
    return response.accessToken;
  });
}

Now, wait for it before making protected requests:

Option 1: Use .then() chaining

function fetchProtectedData() {
  // First refresh the token, then use it for the protected request
  return refreshAccessToken()
    .then(newToken => {
      return fetch('/api/protected-data', {
        headers: { 'Authorization': `Bearer ${newToken}` }
      });
    })
    .then(res => res.json())
    .then(data => {
      console.log('Protected data:', data);
      return data;
    });
}

Option 2: Use async/await (more readable for sequential async steps)

async function fetchProtectedData() {
  try {
    // Wait for the token refresh to complete
    const newToken = await refreshAccessToken();
    // Then make the protected request
    const res = await fetch('/api/protected-data', {
      headers: { 'Authorization': `Bearer ${newToken}` }
    });
    const data = await res.json();
    console.log('Protected data:', data);
    return data;
  } catch (err) {
    // Handle errors here (e.g., refresh token expired)
    console.error('Failed to refresh token or fetch data:', err);
  }
}

A quick sanity check: if refreshAccessToken() wasn't returning the Promise at all, that would also cause it to return undefined immediately. Always make sure your async functions return the Promise they're working with!

内容的提问来源于stack exchange,提问作者Mr.Smithyyy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:20:18