Skip to content

Instantly share code, notes, and snippets.

@liang799
Last active September 27, 2022 01:24
Show Gist options
  • Save liang799/8d17460669bf2983773cea930ce43919 to your computer and use it in GitHub Desktop.
Save liang799/8d17460669bf2983773cea930ce43919 to your computer and use it in GitHub Desktop.
Recaping javascript before internship

Async functions

Write Asynchronous code (promises) in a synchronous manner

Await

makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Asynchronous concept

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

Callbacks

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

function greeting(name) {
  alert(`Hello, ${name}`);
}

function processUserInput(callback) {
  const name = prompt("Please enter your name.");
  callback(name);
}

processUserInput(greeting);

Problems

function doStep1(init, callback) {
  const result = init + 1;
  callback(result);
}

function doStep2(init, callback) {
  const result = init + 2;
  callback(result);
}

function doStep3(init, callback) {
  const result = init + 3;
  callback(result);
}

function doOperation() {
  doStep1(0, (result1) => {
    doStep2(result1, (result2) => {
      doStep3(result2, (result3) => {
        console.log(`result: ${result3}`);
      });
    });
  });
}

doOperation();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Events: Task 2</title>
<style>
p {
color: purple;
margin: 0.5em 0;
}
* {
box-sizing: border-box;
}
canvas {
border: 1px solid black;
}
</style>
<link rel="stylesheet" href="../styles.css" />
</head>
<body>
<section class="preview"></section>
<canvas width="480" height="320" tabindex="0"> </canvas>
<script>
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function drawCircle(x, y, size) {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.fillStyle = "black";
ctx.arc(x, y, size, 0, 2 * Math.PI);
ctx.fill();
}
let x = 50;
let y = 50;
const size = 30;
drawCircle(x, y, size);
// Add your code here
canvas.addEventListener("keydown", (e) => {
switch (e.key) {
case "w":
y -= 20;
break;
case "a":
x -= 20;
break;
case "s":
y += 20;
break;
case "d":
x += 20;
break;
}
drawCircle(x, y, size);
});
</script>
</body>
</html>

Func

Arrow functions

  • auto-bound methods
  • No need to care about binding this to correct value if assign to a variable
  • don't have their own bindings to this, arguments or super, and should not be used as methods directly

Promises

  • Try to use these instead of callbacks.
  • Asynchronous
  • Similar to event listeners
  • represents the current state of the operation
  • promise is fulfilled (kept) / rejected (broken) / pending

Simple example

getJSON("/api/usr/profile").then(displayProfile, handleError)

/* A more Readable approach: */
getJSON("/api/usr/profile").then(displayProfile).catch(handleError)

Get the JSON containing user, then display the user's profile

Chaining Promises

Bad Practise

Nesting hell

const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');

fetchPromise.then((response) => {
  const jsonPromise = response.json();
  jsonPromise.then((data) => {
    console.log(data[0].name);
  });
});

Good Practise

the elegant feature of promises is that then() itself returns a promise, which will be completed with the result of the function passed to it. This means that we can (and certainly should) rewrite the above code like this:

const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');

fetchPromise
  .then((response) => response.json())
  .then((data) => {
    console.log(data[0].name);
  });

Workers

  • Basically multithreading, but no common variable.
  • No more locking, sleeping and whatnot.
  • Workers and the main code run in completely separate worlds
  • Workers interact by sending each other messages and have no access to the DOM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment