TIL024_210418

keepcalmยท2021๋…„ 4์›” 19์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
24/33
post-thumbnail

๐ŸŠ ๊ฐ์ƒ

๐Ÿ“™ ์—ดํ’ˆํƒ€ ์ฝ”๋”ฉ ์‹œ๊ฐ„ 10hour
๐Ÿ‘๐Ÿผ -
๐Ÿ‘Ž๐Ÿผ -

๐Ÿš€ ๋ชฉํ‘œ

  • Udemy์—์„œ Javascript ๊ฐ•์ขŒ ์ˆ˜๊ฐ•ํ•˜๊ธฐ (332/682)
  • ๊ฐœ์ธ ํ”„๋กœ์ ํŠธ ์ง„ํ–‰

๐Ÿ“ฃ The Web Developer Bootcamp 2021

27. Async

272. Web APIs & Single Thread

single thread

At any given point in time, that single JS thread is running at most one line of JS code.
JS is running one line of code at a time

console.log("1")
setTimeout(() => {
  console.log("2")},3000)
console.log("3")
//1 3 2

์‹ฑ๊ธ€์Šค๋ ˆ๋“œ๋ผ๋ฉด 1 2 3 ์œผ๋กœ ์ถœ๋ ฅ๋ผ์•ผ ํ•˜๋Š” ๊ฒƒ ์•„๋‹Œ๊ฐ€? -> ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์ผํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์•„๋‹ˆ๋‹ค!
๋ธŒ๋ผ์šฐ์ €๋Š” C++๊ฐ™์€ ๊ฒƒ์œผ๋กœ ์ž‘์„ฑ๋๊ณ , ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๊ฐ€ ๋ชปํ•˜๋Š” ์ผ ํ•ด๋ƒ„
์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๊ฐ€ ์–ด๋Š ์‹œ์ ์—์„œ ๋ธŒ๋ผ์šฐ์ €์—๊ฒŒ ์ผ์„ ๋„˜๊ธฐ๊ณ , ์ด๋ฅผ Web API๋ผ๊ณ  ๋ถ€๋ฆ„
Web API๋Š” ๋ฉ”์†Œ๋“œ๊ฐ™์€ ๊ฒƒ

callback / callback queue / web APIs

273. callback hell

//generic function and callback
const delayedColorChange = (newColor, delay, doNext) => {
  setTimeout(() => {
    document.body.style.backgroundColor = newColor;
    doNext && doNext();
  }, delay);
};

delayedColorChange('red', 1000, () => {
  delayedColorChange('orange', 1000, () => {
    delayedColorChange('yellow', 1000, () => {
      delayedColorChange('green', 1000, () => {
        delayedColorChange('blue', 1000, () => {});
      });
    });
  });
});

searchMoviesAPI(
  'amadeus',
  () => {
    saveToMyDB(
      movies,
      () => {
        //if it works, run this:
      },
      () => {
        //if it doesn't work, run this:
      }
    );
  },
  () => {
    //if API is down, or request failed
  }
);

274. fakeRequest Using Callbacks

a promise is an object representing the eventrual completion or failure of an asynchronous operation

275. fakeRequest Using Promises

promise is the eventual guarantee of either a value or an error
pending, resolved, rejected
a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function

const request = fakeRequestPromise('yelp.com/api/coffee/page1');
request //object - pass callback both of them and only one will run
  .then(() => {
    //method1
    console.log('It Worked (page1)');
    //if resolved, print this out
    fakeRequestPromise('yelp.com/api/coffee/page2')
      .then(() => {
        console.log('It Worked (page2)');
        fakeRequestPromise('yelp.com/api/coffee/page3')
          .then(() => {
            console.log('It Worked (page3)');
          })
          .catch(() => {
            console.log('Error (page3)');
          });
      })
      .catch(() => {
        console.log('Error (page2)');
      });
  })
  .catch(() => {
    //method2
    console.log('Error (page1)');
    //if rejecte d, print this out
  });

276. The magic of Promises

fakeRequestPromise('yelp.com/api/coffee/page1')
  .then((data) => {
    console.log('Worked(page1)');
    console.log('data');
    return fakeRequestPromise('yelp.com/api/coffee/page2');
  })
  .then((data) => {
    console.log('Worked(page2)');
    console.log('data');
    return fakeRequestPromise('yelp.com/api/coffee/page3');
  })
  .then((data) => {
    console.log('Worked(page3)');
    console.log('data');
  })
  .catch((error) => {
    console.log('Request Failed');
    console.log('error');
  });

277. Creating our own promises

const delayedColorChange = (color, delay) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      document.body.style.backgroundColor = color;
      resolve();
    }, delay);
  });
};

delayedColorChange('red', 1000)
  .then(() => delayedColorChange('orange', 1000))
  .then(() => delayedColorChange('yellow', 1000))
  .then(() => delayedColorChange('green', 1000))
  .then(() => delayedColorChange('blue', 1000));

278. The Async keword

a newer and cleander syntax for working with async code
syntax "makeup" for promises - syntax sugar
2 pieces - async, await

async

async functions always return a promise
if the function returns a value, the promise will be resolved with that value
if the function throws and exception, the promise will be rejected

const login = async (username, password) => {
  if (!username || !password) throw 'Missing Credentials';
  if (password === 'corgifeetarecute') return 'Welcome';
  throw 'Invalid password';
};
login('sasdf', 'corgifeetarecute')
  .then((msg) => {
    console.log('logged in');
    console.log(msg);
  })
  .catch((err) => {
    console.log('error');
    console.log(err);
  });
//logged in Welcome
//error Invalid password
//error Missing credentials

279. The await keyword

We can only use the await keyword inside of functions declared with async
await will pause the execution of the function, waiting for a promise to be resolved before continuing on.

async function rainbow() {
  await delayedColorChange('red', 1000);
  await delayedColorChange('orange', 1000);
  await delayedColorChange('yellow', 1000);
  await delayedColorChange('green', 1000);
  return 'All done';
}
//1
{
  rainbow().then(() => console.log('End of rainbow'));
}
//2
{
  async function printRainbow() {
    await rainbow();
    console.log('End of rainbow');
  }
}

280. Handling errors in async functions

e -> error

async function makeTwoRequests() {
  try {
    let data1 = await fakeRequest('/page1');
    console.log(data1);
    let data2 = await fakeRequest('/page2');
    console.log(data2);
  } catch (e) {
    console.log('Caught an error');
    console.log('error is:', e);
  }
}

28. AJAX and API's

282. Intro to AJAX

AJAX = asynchronous javascript and xml
์—์ด์ ์Šค ๋น„๋™๊ธฐ ํ†ต์‹  ๊ธฐ์ˆ 

์ฐธ๊ณ ๋งํฌ: ์ด๋“ 

markup language html๋ณด๋‹ค ๋” ๊ฐ•๋ ฅํ•˜๊ณ  ํ™•์žฅ ๊ฐ€๋Šฅํ•œ ์–ธ์–ด๊ฐ€ xml
xml = exentensible markup language : ๊ณผ๊ฑฐ ๋งŽ์ด ์‚ฌ์šฉ๋˜๋˜ ๋ฐ์ดํ„ฐ ํฌ๋งท
์ตœ๊ทผ์—๋Š” xml์ด ์•„๋‹Œ json์„ ์‚ฐ์—…์˜ ํ‘œ์ค€์œผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค
json: javascript object notation
ajax๋Š” ์ด๋Ÿฌํ•œ ๊ธฐ์ˆ ๋“ค์— ๋Œ€ํ•œ ํ†ตํ•ฉ๋ช…์นญ - ๋น„๋™๊ธฐ ํ†ต์‹ ์„ ์œ„ํ•œ ๊ธฐ์ˆ  ๋ฌถ์Œ
classic web application model : browser client: fron-end / sever-side system: back-end -> ๋ญ”๊ฐ€ ํด๋ฆญํ•˜๊ณ  ์š”์ฒญ ์š”๊ตฌํ•  ๋•Œ๋งˆ๋‹ค ๋งค๋ฒˆ ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์™€์•ผ ํ•จ, ๋‹ค์‹œ ํ™”๋ฉด ๊ตฌ์„ฑ

AJAX: ๋ธŒ๋ผ์šฐ์ €์— AJAX ์—”์ง„ ํฌํ•จ, ์š”์ฒญ/์‘๋‹ต ๊ณผ์ •์„ ํ†ตํ•ด ๋ถˆํ•„์š”ํ•œ ๋ถ€๋ถ„๊นŒ์ง€ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๋Š”๋‹ค
ํ•„์š”ํ•œ ๋ถ€๋ถ„๋งŒ ๋ณ„๋„๋กœ ์š”์ฒญํ•˜๊ณ  ์‘๋‹ต ๋ฐ›์•„ ์ฒ˜๋ฆฌ-> ๋ถˆํ•„์š”ํ•œ ๋Œ€์—ญํญ ๊ฐ์†Œ, ๋น„์šฉ ์ ˆ๊ฐ

classic web application model ์€ ๋™๊ธฐ, ajax๋Š” ๋น„๋™๊ธฐ
์‚ฌ์šฉ์ž ๋Œ€๊ธฐ ์‹œ๊ฐ„ ์ค„์ด๊ณ  ํŽ˜์ด์ง€ ์ƒˆ๋กœ๊ณ ์นจํ•˜์ง€ ์•Š๊ณ ๋„ ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋งŒ ๋ฐ›์•„์™€์„œ ์—…๋ฐ์ดํŠธ

ajax ์šฉ์–ด์— xml์ด ํฌํ•จ๋ผ ์žˆ์–ด์„œ xml๋งŒ ํ†ต์‹  ๊ฐ€๋Šฅํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ๊ฒ ์ง€๋งŒ ์•„๋‹˜,
xml, text, html, json ๊ฐ€๋Šฅ -> ๊ทธ ์ค‘ json์ด ํ‘œ์ค€์œผ๋กœ ์“ฐ์ž„

283. Intro to APIs

Web apis = http based
APIs are like a portal into a different application or database somewhere or a data set

cryptonator api
openweather api
twitter api
facebook api
twilio api

284. WTF is JSON

has key value pairs : but every key has to be a double quoted string

json.org
undefined is not valid in json

static methods

JSON.parse -> json will be parsed into a javascript object

data
const parsedData = JSON.parse(data)
parsedData.ticker
parsedData.ticker.price

stringify : ๋ฐ˜๋Œ€๋กœ

285. Using Postman

postman.com
http status code
icanhazdadjoke api

playing and testing APIs

status code : 200 ok / 404 not found - quick indicator of what happend

headers: bunch of key-value pairs, kind of like the metadata for the response and also for the request

286. query strings & headers

tvmaze api

url: /search/shows?q=:query ์—์„œ
:๊ฐ€ ์˜๋ฏธํ•˜๋Š” ๊ฒƒ์€ :query๊ฐ€ variable์ด๋ผ๋Š” ๊ฒƒ

?q=:query๋Š” query string ์ž„ - way of providing additional information to a request
search stirng์ด๋ผ ๋ถˆ๋ฆฌ๊ธฐ๋„ ํ•จ
q=:query๋Š” parameters that are being passed off to the server

์ฐธ๊ณ ๋งํฌ: ์˜ค์œค์ƒ
์ฐธ๊ณ ๋งํฌ: Doyoon Lee

287. Making XHR's

XMLHttpRequest
: the original way of sending requests via JS
does not support promises, so lots of callbacks
wtf is going on with the weird capitalization
cluncky syntax that i find difficult to remember

const req = new XMLHttpRequest();
//make an object - new xml http request that gives us a new request object

req.onload = function () {
  console.log('all done with request');
  const data = JSON.parse(this.responseText);
  console.log(data.ticker.price);
};
//attach onload callback
//this: object req = XMLHttpRequest

req.onerror = function () {
  console.log('error');
  console.log(this);
};
//attach onerror callback

req.open('get', 'https://api.cryptonator.com/api/full/btc-usd');
//(method = get request, second argument=url)
req.send();

288. The Fetch API

the newer way of making requests via JS
supports promises (promise based, no have to worry about callback)
not supported in internet explorer :(

// 1. promise version
fetch('https://api.cryptonator.com/api/full/btc-usd')
  //is going to return a promise
  //resolved with the response object
  //response object has a bunch of stuff like status code, headers
  .then((res) => {
    console.log('response, waiting to parse', res);
    return res.json();
    //*this returns promise so I can chain it
  })
  .then((data) => {
    console.log('data parsed');
    console.log(data.ticker.price);
  })
  .catch((e) => {
    console.log('oh no error', e);
  });
//as soon as it gets the first bit of headers,
//fetch is going to resolve the promise
//so i'm not guaranteed to have the body, the content that I want
//*-> that's why we use a second method called .JSON

// 2. async version

const fetchBitcoinPrice = async () => {
  try {
    const res = await fetch('https://api.cryptonator.com/api/full/btc-usd');
    const data = await res.json();
  } catch (e) {
    console.log('something went wrong', e);
  }
};

289. Intro to Axios

a library for making http requests
two separate steps (fetch & .json)-> single steps , a lot easier and just shorter

github axios
intalling - using jsdelivr cdn

//1
axios.get('https://api.cryptonator.com/api/full/btc-usd')
  .then(res => {
    console.log(res.data.ticker.price)
  // we already have our response object fully parsed
  })
  .catch(err => {
    console.log("error", err)
  })
//2
const fetchBitcoinPrice = async () => {
  try {
    const res = await axios.get('https://api.cryptonator.com/api/full/btc-usd')
    console.log(res.data.ticker.price)
  } catch (e) {
    console.log("error", e)
  }
}

290. Setting headers with axios

์ฐธ๊ณ ๋งํฌ: ๊ฐ“๋Œ€ํฌ
์ฐธ๊ณ ๋งํฌ: ์ •์•„๋งˆ์ถ”์–ด

const jokes = document.querySelector('#jokes');
const button = document.querySelector('button');
//ul id = "jokes"

const addNewJoke = async () => {
  const jokeText = await getDadJoke();
  const newLI = document.createElement('LI');
  newLI.append(jokeText);
  jokes.append(newLI);
};

const getDadJoke = async () => {
  try {
    const config = { headers: { accept: 'application/json' } };
    const res = await axios.get('https://icanhazdadjoke.com/', config);
    return res.data.joke;
  } catch (e) {
    return 'no jokes available';
  }
};

button.addEventListener('click', addNewJoke);

291. The show search app

{
  /* <form>
    <input type="text" placeholder="tv show title"/>
    <button>search</button>
</form> */
}

const form = document.querySelector('#searchForm');
form.addEventListener('submit', async function (e) {
  e.preventDefault();
  const searchTerm = form.elements.query.value;
  const config = { params: { q: searchTerm } };
  const res = await axios.get(`http://api.tvmaze.com/search/shows`, config);
  makeImages(res.data);
  form.elements.query.value = '';
});

const makeImages = (shows) => {
  for (let result of shows) {
    if (result.show.image) {
      const img = document.createElement('IMG');
      img.src = result.show.image.medium;
      document.body.append(img);
    }
  }
};

Like with any technology or tool th at you might be using, you would need to check its documentation to find out about the options that you have. In this case, make sure to check the axios documentation for params that you can pass while configuring your axios request: https://github.com/axios/axios#request-config

So, in this example, the name config is a variable name that we arbitrarily chose, but it holds an object with the params key which the axios request will understand when we pass it as an argument. The key q is something that the particular API that we are using expects. To know what params we can pass to an API, we need to study the API documentation for the route/address that we are sending a request to - that way we can know of all the options/params supported by the API endpoint in question.

29. Prototypes, classes & OOP

291. Prototypes

arr.sing = function() {console.log("lalala")
//-> arr์— sing์ด๋ผ๋Š” function์ด ์ถ”๊ฐ€๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Œ
arr.push(5)
//push๋Š” arr method์—์„œ ๋ณผ ์ˆ˜ ์—†์Œ. _proto_๋ผ๋Š” property์— ์ด๋ฏธ ๋“ค์–ด๊ฐ€์žˆ์Œ -> prptotype 
console.dir(body) 
//it has certain properties that are specific to this body & prototype  

prototype = object, contain typically a bunch of methods
string.prototype ๋„ ์žˆ์Œ

//์ด๋Ÿฐ ์‹์œผ๋กœ ์šฐ๋ฆฌ๋งŒ์˜ ๋ชจ๋“  string์— ์ ์šฉ๋˜๋Š” prototype์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค
String.prototype.yell = function() {
  return `omg ${this.toUpperCase()}`;
};

"i love you".yell();
//overrrideํ•  ์ˆ˜๋„ ์žˆ์Œ

prototype: single object that contains common properties and methods that other copies and other objects or other strings look up to find their common properties
place to store things, template, blueprint

Array.prototype
-> actual object, where we add the methods or the properties, template object
actual prototype object that i can add on to,

_proto_
-> this is a reference, is a property name on this array or on the string,
reference to the prototype

intro to object oriented programming

it's cut from the same cookie cutter that all other heading elements are (html heading elements)

console.dir(document.querySelector('h1'))

๐Ÿ•น Project

์Œ์•… DB ์‚ฌ์ดํŠธ ํ”„๋กœ์ ํŠธ ์‹œ์ž‘

glassmorphism

z-index

bigger the number, more forward
default: 1

gradient

background: linear-gradient(to right top, #fff, #fff);

blur

backdrop-filter: blur(2rem);

0๊ฐœ์˜ ๋Œ“๊ธ€