Home

Promise consumers - then, catch, finally

A Promise object serves as a link between the executor (the “producing code” or “singer”) and the consuming functions (the “fans”), which will receive the result or error. Consuming functions can be registered (subscribed) using methods .then, .catch and .finally. then The most important, fundamental one is .then. The syntax is: promise.then(...

Read more

Promise

Imagine that you’re a top singer, and fans ask day and night for your upcoming single. To get some relief, you promise to send it to them when it’s published. You give your fans a list. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wr...

Read more

Flatten javascript object to single depth array

snippet: // flatten object to one depth const obj = { 'name': 'jane', 'last_name': 'doe', 'profession': 'engineer', 'characteristics': { 'intelligent': true, 'punctual': false, 'experience': { '2012': 'college passout', '2014': 'mba passout', '2016': 'employed' } } }; function flattenObject(ob, prefix) { const toReturn ...

Read more

Callbacks

Many actions in JavaScript are asynchronous. In other words, we initiate them now, but they finish later. For instance, we can schedule such actions using setTimeout. There are other real-world examples of asynchronous actions, e.g. loading scripts and modules (we’ll cover them in later chapters). Take a look at the function loadScript(src), ...

Read more

Callback in callback or callback hell or pyramid of doom

How can we load two scripts sequentially: the first one, and then the second one after it? The natural solution would be to put the second loadScript call inside the callback, like this: loadScript('/my/script.js', function(script) { alert(`Cool, the ${script.src} is loaded, let's load one more`); loadScript('/my/script2.js', function(sc...

Read more

Wrapping exceptions

The purpose of the function readUser is “to read the user data”. There may occur different kinds of errors in the process. Right now we have SyntaxError and ValidationError, but in the future readUser function may grow and probably generate other kinds of errors. The code which calls readUser should handle these errors. Right now it uses multip...

Read more

try..catch with setTimeout

try..catch works synchronously. If an exception happens in “scheduled” code, like in setTimeout, then try..catch won’t catch it: Example: try { setTimeout(function() { noSuchVariable; // script will die here }, 1000); } catch (e) { alert( "won't work" ); } To catch an exception inside a scheduled function, try..catch must be insi...

Read more