Created
July 10, 2016 22:26
-
-
Save auchomage/8e40e2165a00be528b0961a7b98bc1c4 to your computer and use it in GitHub Desktop.
Node.JS callbacks - question 1: I have 2 files (1) decon_t2_calledFile.js and (2) decon_t2_callingFile.js. My aim is to take the string output of file 1 (decon_t2_calledFile.js) and access through file 2 (decon_t2_callingFile.js))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function(callback){ | |
function () { | |
// Contents of this anonymous function will serve as output | |
// from this file | |
console.log('** Output from decon_t2_calledFile.js ** '); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var someInput = require('./decon_t2_calledFile.js'); | |
// display contents of 'decon_t2_calliedFile.js' | |
someInput(function(callback){ | |
callback(); | |
}); // should display ('** Output from decon_t2_calledFile.js ** |
You could say it's the result of the callback function. That would be appropriate.
A callback is generally defined as a function that runs after something else runs.
What does that statement mean in the context of :
//decon_t2_callingFile.js
var someFunction = require('./decon_t2_calledFile.js');
// display contents of 'decon_t2_calliedFile.js'
someFunction(function(myString){
console.log(myString);
});
What else is happening here? This will help me to identify it in future, as my previous definition of merely placing a function inside another function is wrong.
Thanks Andrew.
That "something else" would be anything asynchronous like fetching a webpage or making a database request. If you have synchronous code, callbacks are really adding any value because a simple return
statement could get the job done just fine.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this example we are working with, is that 'something else' equivalent to ' someFunction()'?
In the following example, we can see that the something else is a click event.
displayTodosButton.addEventListener('click', function(){ todoList.displayTodos(); });
Separate question:
Is it correct to say that
callback('some text');
Will result in 'some text' being generated as output?