This video discusses callbacks that take arguments and how they are used in JavaScript. We give an example using fs.readFile, which passes errors and results into our callback function. We talk about a very common mistake in asynchronous programming and how to avoid it.
- [Narrator] With our simple setTimeout example,…the function we passed was a function with no arguments.…This is actually very rarely the case.…Most asynchronous functions that we perform…pass the results of the operation…to our function as an argument.…For example, it might pass the results that we obtain…when reading from a database or reading a file.…In Node.js especially, the standard form is…to pass the result of the asynchronous function…as the second argument, and any errors…the function encounters as the first argument.…
As an example, let's take a look…at how we read a file asynchronously in Node.js.…Fs is a standard library included with Node.js…that allows us to work with the file system.…Note that we don't have to use npm to install it.…Now, when we read a file using fs.readFile,…the results of opening the file are passed to our function.…The first argument will contain any errors…that occurred during the operation…such as if the file didn't exist,…and the second one will contain the data from the file.…
Released
7/14/2017- What's functional programming?
- Functional vs. object-oriented programming
- First-class functions
- Higher-order functions
- Array functions
- Mapping, filtering, and reducing
- Simple callbacks
- Callbacks with arguments
Share this video
Embed this video
Video: Callbacks with arguments