-
Notifications
You must be signed in to change notification settings - Fork 7
Async
- To use this module do require('fs')
- Strongly encouraged to use asynchronous
- Synchronous versions will block the entire process until they complete
- Continuation-Passing Style (CPS) name for how Node.js uses callbacks
- Node.js relies on asynchronous code to stay fast
- The first argument of the callback is reserved for an error object
- If an error occurred, it will be returned by the first err argument.
- The second argument of the callback is reserved for any successful response data
-
If no error occurred, err will be set to null and any successful data will be returned in the second argument
fs.readFile('/foo.txt', function(err, data) { // If an error occurred, handle it (throw, propagate, etc) if(err) { console.log('Unknown Error'); return; } // Otherwise, log the file contents console.log(data); }); -
Propagate the error based on the information and context that exist at that level
`if(err) { // Handle "Not Found" by responding with a custom error page if(err.fileNotFound) { return this.sendErrorMessage('File Does not Exist'); } // Ignore "No Permission" errors, this controller knows that we don't care // Propagate all other errors (Express will catch them) if(!err.noPermission) { return next(err); } }` -
Callbacks can be called in parallel, in a queue, in serial, or any other combination you can imagine
`// Example taken from caolan/async README async.parallel({ one: function(callback){ setTimeout(function(){ callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function(){ callback(null, 2); }, 100); } },function(err, results) { // results is equal to: {one: 1, two: 2} });`
-
- An asynchronous model allows multiple things to happen at the same time
- One approach to asynchronous programming is to make functions that perform a slow action take an extra argument, a callback function
- The action is started, and when it finishes, the callback function is called with the result
- A promise is an asynchronous action that may complete at some point and produce a value
- It is able to notify anyone who is interested when its value is available
- The easiest way to create a promise is by calling
Promise.resolve - To create a promise, you can use Promise as a constructor
- Asynchronous programs are executed piece by piece
- the JS engine has had no innate sense of time, but has instead been an on-demand execution environment for any arbitrary snippet of JS
- The surrounding environment that has always scheduled "events" (JS code executions)
- Event loop
- The surrounding environment that has always scheduled "events" (JS code executions)
- Async is about the gap between now and later
- Parallel is about things being able to occur simultaneously
- Callbacks express asynchronous flow in a rather nonlinear, nonsequential way
- Suffer from inversion of control in that they implicitly give control over to another party (often a third-party utility not in your control!) to invoke the continuation of your program
- They solve the inversion of control issues that happen with callbacks
- It's a future value
- Important characteristic of future values: they can either indicate a success or failure
- Once a Promise is resolved, it stays that way forever -- it becomes an immutable value at that point -- and can then be observed as many times as necessary
-
An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result
`async function name([param[, param[, ... param]]]) { statements }` -
An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and evaluates as the resolved value
- Mocking is a technique to isolate test subjects by replacing dependencies with objects that you can control and inspect
- A dependency can be anything your subject depends on
- It is typically a module that the subject imports
- Mocking in Jest -> replacing dependencies with the Mock Function
-
The goal of mocking is to replace something we don't control with something we do
-
The Mock Function provides features to:
- Capture calls
- Set return values
- Change the implementation
-
The simplest way to create a Mock Function instance is with jest.fn()
`test("returns undefined by default", () => { const mock = jest.fn(); let result = mock("foo"); expect(result).toBeUndefined(); expect(mock).toHaveBeenCalled(); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith("foo"); });`
- There are three main types of module and function mocking in Jest:
- jest.fn: Mock a function
- jest.mock: Mock a module
- jest.spyOn: Spy or mock a function