如何在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 combinedname,title, andgenderdata upward. printResult()isn’t implemented to trigger the sequence of callback functions and capture the final data fromaddGender().
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:
- 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 toprintResult(). - 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 fromaddGender()).
- Start with
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
相关产品推荐
相关产品推荐

