๐ ์ดํํ ์ฝ๋ฉ ์๊ฐ 10hour
๐๐ผ -
๐๐ผ -
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
//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
}
);
a promise is an object representing the eventrual completion or failure of an asynchronous operation
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
});
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');
});
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));
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
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');
}
}
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);
}
}
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์ด ํ์ค์ผ๋ก ์ฐ์
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
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 : ๋ฐ๋๋ก
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
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
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();
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);
}
};
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)
}
}
์ฐธ๊ณ ๋งํฌ: ๊ฐ๋ํฌ
์ฐธ๊ณ ๋งํฌ: ์ ์๋ง์ถ์ด
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);
{
/* <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.
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
it's cut from the same cookie cutter that all other heading elements are (html heading elements)
console.dir(document.querySelector('h1'))
z-index
bigger the number, more forward
default: 1
gradient
background: linear-gradient(to right top, #fff, #fff);
blur
backdrop-filter: blur(2rem);