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

如何在Node.js中修改printResult()函数输出addGender()内容?

Solution: Modify Callback Chain to Pass Data to printResult()

First, let's break down the gaps in your current code:

  • The addGender() function receives a callback parameter but doesn’t use it to pass the combined name, title, and gender data upward.
  • printResult() isn’t implemented to trigger the sequence of callback functions and capture the final data from addGender().

Here’s the modified code that preserves your callback-based architecture and lets printResult() output the content from addGender():

const name = "sam";

function getName(callback) { 
  callback(name); 
}

function addTitle(name, callback) { 
  var title = "writer"; 
  callback(name, title); 
}

function addGender(name, title, callback) { 
  var gender = "male"; 
  // Pass the combined data to the callback instead of logging directly
  callback({ name, title, gender }); 
}

function printResult() {
  // Chain the callbacks to flow data through each function
  getName(function(name) {
    addTitle(name, function(name, title) {
      addGender(name, title, function(finalData) {
        // Output the data from addGender() here in printResult()
        console.log("Final Result:", finalData);
      });
    });
  });
}

// Execute printResult to see the output
printResult();

Key Changes Explained:

  1. Updated addGender(): Instead of logging the object directly, we now pass the {name, title, gender} object to the provided callback. This lets us route the data up the chain to printResult().
  2. Implemented printResult(): We orchestrate the callback sequence step-by-step:
    • Start with getName() to retrieve the name.
    • Pass that name to addTitle() to get the title.
    • Pass both values to addGender() to assemble the full data object.
    • Finally, in the innermost callback, we log the data (this is where printResult() outputs the content from addGender()).

When you run this code, printResult() will output:

Final Result: { name: 'sam', title: 'writer', gender: 'male' }

If you still want addGender() to log the data internally (in addition to printResult()), you can keep the original console.log({name,title,gender}) in addGender() alongside the callback call.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:56:32