Advanced JavaScript

DOM Manipulation

You can select node via JQuery or Document functions

Nodes can be selected via CSS selector or composition of CSS selector

You can also:

get and set attributes of node

Add and remove nodes

Use event listener or attach new one

async

Why async in JavaScript is so important?

UI can't be stopped

But how to manage it?

We have callbacks:

var myFunction = function(a, b, callback){
    var c = a + b;
    callback(c);
};

myFunction(20, 22, function(sum){
    console.log(sum);
    // 42
});

easy to understand but...

 

Pyramid of doom

f1(params, function(r1) {
  f2(r1, function(r2) {
    f3(r2, function(r3) {
      f4(r3, function(r4) {
        f5(r4, function(r5) {
          f6(r5, function(r6) {
            f7(r6, function(r7) {
              f8(r7, function(r8) {
                f9(r8, function(r9) {
                  f10(r9, function(r10) {
                    // CODE...
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});

Promises

A Promise is a proxy for a value not necessarily known when the promise is created
...

A Promise is in one of these states:

  • pending: initial state, not fulfilled or rejected.

  • fulfilled: meaning that the operation completed successfully.

  • rejected: meaning that the operation failed.

 

developer.mozilla.org

States can managed by:
.then(onResolve[, onReject])
.catch(onReject)

 

no Pyramid of doom (if you use in right way)

function1(params).then(function(r1){
  return function2(r1)
}).then(function(r2){
  return function3(r2)
}).then(function(r3){
  return function4(r3)
}).then(function(r4){
  return function5(r4)
}).then(function(r5){
  // CODE ...
});

 

not so "natural" to implement

myFunction1(params).then(function(r1){
    myFunction2(r1).then(function(r2){
        myFunction3(r2).then(function(r3){
            myFunction4(r3).then(function(r4){
                // CODE...
            });
        });
    });
});
var r1;
var r2;

myFunction1(params).then(function(r){
    r1 = r;
});

myFunction2(r1).then(function(r){
    r2 = r;
});

// CODE WHO USE r2

</DON'T TRY THIS AT HOME>

<DON'T TRY THIS AT HOME>

there are also other way to manage like :
async await, generator etc.

That's It!

Thanks!

Advanced JavaScript 2

By extrategy

Advanced JavaScript 2

  • 1,356