PROGRAMOWANIE JAVASCRIPT

Programowanie JavaScript 07

Javascript

Async Await

Async

function hello() { return "Hello" };
hello();
async function hello() { return "Hello" }
hello() // promise

let hello2 = async function() { return "Hello2" }
hello2()

let hello3 = async () => { return "Hello3" }
hello3()

hello().then((value) => console.log(value))
hello2().then((value) => console.log(value))
hello3().then(console.log)

Await

async function hello4() {
  return greeting = await Promise.resolve("Hello4");
};

hello4().then(console.log);

Pros and cons

Meta programming

Proxies - default value

let handler = {
  get: function(target, name) {
    return name in target? target[name] : 'hmmm'
  }
}
let object = { x: 'X' }
let proxy = new Proxy(object, handler)
proxy.a = 'A'
console.log(proxy.a, proxy.b, proxy.x)
proxy.x = 'Y'
console.log(proxy.a, proxy.b, proxy.x)

Revocable Proxy

let revocable = Proxy.revocable({}, {
  get: function(target, name) {
    return '[[' + name + ']]'
  }
})
let proxy = revocable.proxy
console.log(proxy.foo)  // "[[foo]]"

revocable.revoke()

console.log(proxy.foo)  // TypeError is thrown
proxy.foo = 1           // TypeError again
delete proxy.foo        // still TypeError
typeof proxy            // "object", typeof doesn't trigger any trap

Reflection

let myCar = { model: 'fiat' }
Reflect.has(Object, 'assign')
Reflect.has(myCar, 'model')
Reflect.has(myCar, 'year')
if (Reflect.defineProperty(myCar, 'year', {value: 2022})) {
  // success
  console.log(myCar)
  console.log(myCar.year)
} else {
  // failure
}

Ćwiczenia

  1. Dodać dwie metody do klasy Car:
    1. milage - będzie liczony synchronicznie z użyciem await
    2. aMilage - będzie liczony asychronicznie
    3. obie metody zwracają przebieg w km, dodać opcje przeliczania kilometrów na mile (1 kilometr = 0.621371192 mili)
    4. Wyniki wypisywać na ekran z pomocą console.log
  2. Dodać Proxy dla Car, tak aby atrybut engine, miał domyślnie wartość petrol.

hints

function delay(t, v) {
   return new Promise(function(resolve) {
       setTimeout(resolve.bind(null, v), t)
   });
}

Promise.prototype.delay = function(t) {
    return this.then(function(v) {
        return delay(t, v);
    });
}

Promise.resolve("hello").delay(500).then(function(v) {
    console.log(v);
});