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

Node.js中回调函数无法正常工作问题求助

Troubleshooting Async Callback Issues in Your Node.js Code

Let’s break down why your callbacks might not be working as expected, based on the code snippets you shared:

1. getUserFromToken Doesn’t Expose Its Result to Callers

Looking at your getUserFromToken function:

function getUserFromToken(token) { 
  decodeJWT(token, function (err, data) { 
    console.log("Call back Worked"); 
  }) 
}

Right now, this function runs decodeJWT and logs a message, but it doesn’t pass the err or decoded data back to whatever calls getUserFromToken. If you’re trying to use the decoded data elsewhere, you need to add a callback parameter to getUserFromToken itself:

function getUserFromToken(token, callback) { 
  decodeJWT(token, function (err, data) { 
    if (err) {
      console.error("JWT decode failed:", err);
      return callback(err, null);
    }
    console.log("Callback fired successfully");
    callback(null, data);
  }) 
}

Then when you invoke it, handle the result properly:

getUserFromToken("your-auth-token", (err, userData) => {
  if (err) {
    // Handle decoding error (e.g., invalid token)
    return;
  }
  // Use the decoded user data here
  console.log("Decoded user:", userData);
});

2. Unhandled Errors or Silent Failures in getUserProfile

Your getUserProfile function looks structurally correct, but if you’re not checking the error parameter when calling it, you might miss why the callback isn’t returning a result. Always log errors explicitly to debug:

When calling getUserProfile:

getUserProfile(123, "johndoe", "hashed-password", (err, profile) => {
  if (err) {
    console.error("Database query error:", err); // This will reveal connection issues or invalid SQL
    return;
  }
  if (!profile || profile.length === 0) {
    console.log("No user found matching the provided credentials");
    return;
  }
  // Use the retrieved profile data
  console.log("User profile:", profile[0]);
});

Also, double-check that your db connection is properly initialized—if the database isn’t connected, db.query might never trigger the callback at all.

3. Confusing Async Timing with Synchronous Code

A super common pitfall is trying to use the result of an async callback before it fires. For example:

let userProfile;
getUserProfile(123, "johndoe", "hashedpass", (err, profile) => {
  userProfile = profile;
});
console.log(userProfile); // This logs undefined! The callback hasn't run yet.

All code that depends on the async result must live inside the callback (or use promises/async-await instead, which are easier to read).

Bonus: Switch to Promises/Async-Await for Cleaner Code

Callbacks can get messy fast. If your decodeJWT and db.query support promises (or you can promisify them), using async-await will make debugging simpler:

const util = require('util');
// Promisify callback-based functions if needed
const decodeJWTAsync = util.promisify(decodeJWT);
const dbQueryAsync = util.promisify(db.query).bind(db);

async function getUserFromToken(token) {
  try {
    const data = await decodeJWTAsync(token);
    console.log("JWT decoded successfully");
    return data;
  } catch (err) {
    console.error("JWT decode error:", err);
    throw err;
  }
}

async function getUserProfile(user_id, username, hashPass) {
  const sql = "SELECT first_name, last_name, username FROM User where user_id=? AND username=? AND password=?";
  try {
    const result = await dbQueryAsync(sql, [user_id, username, hashPass]);
    return result;
  } catch (err) {
    console.error("Database query error:", err);
    throw err;
  }
}

// Usage example
async function loadUserProfile(token) {
  try {
    const userData = await getUserFromToken(token);
    const profile = await getUserProfile(userData.id, userData.username, userData.hashedPass);
    return profile;
  } catch (err) {
    console.error("Failed to load user profile:", err);
  }
}

loadUserProfile("your-auth-token");

If you can share more details about exactly how your callbacks are failing (e.g., no console log, empty result, specific error messages), I can narrow this down further!

内容的提问来源于stack exchange,提问作者anderish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:30:12