1/5
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Do not abuse in-place function definitions when defining callback. (What are the 3 callbacks discipline?)
These are some basic principles that can help us keep the nesting level low and
improve the organization of our code in general:
Exit as soon as possible. Use return, continue, or break, depending on the context, to immediately exit the current statement instead of writing (and nesting) complete if...else statements. This will help to keep our code shallow.
Create named functions for callbacks, keeping them out of closures and passing intermediate results as arguments. Naming our functions will also make them look better in stack traces.
Modularize the code. Split the code into smaller, reusable functions whenever possible.
Early return principle. (What it is in callback discipline?)
Identifying reusable pieces of code
As a second optimization for our code function, we can try to identify reusable pieces of code. (img for exmaple)
Now that you know how to write clean asynchronous code using callbacks, we are ready to explore some of the most common asynchronous patterns, such as sequential and parallel execution.
Sequential execution
Executing a set of tasks in sequence means running them one at a time, one after the other. The order of execution matters and must be preserved, because the result of a task in the list may affect the execution of the next.
Sequential execution, despite being trivial when implemented using a direct style blocking API, is usually the main cause of the callback hell problem when using asynchronous CPS.
Executing a known set of tasks in sequence
The pattern described in the img works perfectly if we know in advance what and how many tasks are to be executed. This allows us to hardcode the invocation of the next task in the sequence, but what happens if we want to execute an asynchronous operation for each item in a collection? In cases such as this, we can't hardcode the task sequence anymore; instead, we have to build it dynamically.