vef1-2024

Vefforritun 1 kennd haustið 2024

View the Project on GitHub vefforritun/vef1-2024

Fyrirlestur – Ósamstillt forritun

Vefforritun 1 — TÖL107G

Ólafur Sverrir Kjartansson, osk@hi.is


Ósamstillt forritun (async programming)


Samstillt forritun


Dæmi um mismunandi forritun


Callbacks


// snoozea í 5s, síðan 3s og að lokum 1s
setTimeout(() => {
  alert('Vakna!');
  setTimeout(() => {
    alert('Vakna núna!');
    setTimeout(() => {
      alert('VAKNA!!');
    }, 1000);
  }, 3000);
}, 5000);


function snooze(s, msg, callback) {
  setTimeout(() => {
    alert(msg);
    if (callback) {
      callback();
    }
  }, 1000 * s);
}

snooze(5, 'Vakna', () => {
  snooze(3, 'Vakna núna!', () => {
    snooze(1, 'VAKNA!!');
  });
});


Promises





const fifteen = Promise.resolve(15);
fifteen
  .then(v => console.log(`Got ${v}`));
// → Got 15
setTimeout(() => {
  fifteen
    .then((value) => {
      console.log('Sama svar, sekúndu seinna', value)
    });
}, 1000);


Villur


snooze(5, 'Vakna', () => {
  if (ok) {
    snooze(3, 'Vakna núna!', () => {
      if (okok) {
        snooze(1, 'VAKNA!!');
      } else {
        // villa
      }
    });
  } else {
    // villa
  }
});


function futureMessage(msg) {
  return new Promise((resolve, reject) => {
    if (msg === 'foo') {
      reject(new Error('No foo!'));
    }

    setTimeout(() =>
      resolve(`${msg} from future`), 2000);
  });
}

futureMessage('Hi!')
  .then(msg => console.log(msg));
// "Hi! from future!" eftir 2 sek

futureMessage('foo')
  .then(msg => console.log(msg))
  .catch(e => console.log(e));
// "No foo!" strax

Stöður á promise

Promise getur verið í einni af þrem stöðum:


const p = futureMessage('hmm');
function foo(promise) {
  console.log(promise);

  promise.then(msg => console.log(msg));

  return 'Handling promise...';
}
foo(p);
// Promise { ... }
// "Handling promise..."
// "hmm from the future!" eftir 2 sek

function snooze(s, msg) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(msg);
    }, s * 1000);
  });
}

snooze(5, 'Vakna')
  .then(msg => alert(msg))
  .then(() => snooze(3, 'Vakna núna!'))
  .then(msg => alert(msg))
  .then(() => snooze(1, 'VAKNA!!!'))
  .then(msg => alert(msg));


Promise.all


Promise.race


const snoozefest = Promise.all([
  snooze(5, 'Vakna'),
  snooze(3, 'Vakna núna!'),
  snooze(1, 'VAKNA!!!'),
])
  .then(result => console.log(result));

console.log(snoozefest);
// Promise {pending}
// 5s seinna..
// ["Vakna", "Vakna núna!", "VAKNA!!!"]

// snooze eins og áður

Promise.race([
  snooze(5, 'Vakna'),
  snooze(3, 'Vakna núna!'),
  snooze(1, 'VAKNA!!!'),
])
  .then(result => console.log(result));

// 1s seinna..
// "VAKNA!!!"


async og await


// snooze fall eins og áður
async function snoozer() {
  alert(await snooze(5, 'Vakna'));
  alert(await snooze(3, 'Vakna núna'));
  alert(await snooze(1, 'VAKNA!!!'));
}

snoozer();

// futureMessage eins og áður
async function future() {
  try {
    const res = await futureMessage('foo');
    console.log(res);
  } catch (e) {
    console.log(e);
  }
}

future();


async forritun