Generator,Promise,Async Await - ChoDragon9/posts GitHub Wiki
Generator
Breaking Block
- ํ๋ก๊ทธ๋จ์ ์ค๋์ ๋ฉ์ท๋ค๊ฐ ๋ค์ ์คํํ ์ ์์
- yield๋ฅผ ์ด์ฉํ๋ฉด ๋ธ๋ก์ ์ค๊ฐ์ ๋์ด์ฃผ๋ ํจ๊ณผ๊ฐ ๋ฐ์
const infinity= (function*(){
let i = 0;
while(true) yield i++;
})();
console.log(infinity.next());
....
console.log(infinity.next());
Promise
[Callback] Passive Async Control
์ฝ๋ฐฑ์ ๋ณด๋ผ ์๋ ์์ง๋ง ์ธ์ ์ฌ์ง๋ ๋ชจ๋ฅธ๋ค.
$.post(url. data, e=>{ // ์ธ์ ์คํ ๋๋ ๊ฐ })
ํ์ค์ ์ผ๋ก ๋ค์์ API ์์ฒญ์ ํตํด ๊ฒฐ๊ณผ๋ฅผ ๋ง๋ค๊ธฐ ๋๋ฌธ์ ์ธ์ ์๋ต์ด ์ค๋ ์ง ์ค์ํ๋ค.
let result;
$.post(url1, data1, v => {
result = v;
});
$.post(url2, data2, v => {
result.nick = v.nick;
report(result);
});
[Promise] Active Async Control
ํ๋ก๋ฏธ์ค๋ then
์ ํธ์ถํด์ผ ๊ฒฐ๊ณผ๋ฅผ ์ป๋ ๋ค.
let result;
const promise = new Promise(r => $.post(url1, data1, r));
promise.then(v => {
result = v;
});
const promise1 = new Promise(r => $.post(url1, data1, r));
const promise2 = new Promise(r => $.post(url2, data2, r));
promise1.then(result => {
promise2.then(v => {
result.nick = v.nick;
report(result);
});
});
Generator + Promise
const profile = function*(end, r) {
const userid = yield new Promise(res => $.post('member.php', {r}, res));
let added = yield new Promise(res => $.post('detail.php', {userid}, res));
added = added.split(",");
end({userid, nick: added[0], thumb: added[1]});
};
const executor = (gene, end, ...arg) => {
const iter = gene(end, ...arg);
const next = ({value, done}) => {
if (!done) value.then(v => next(iter.next(v)));
};
next(iter.next());
};
executor(profile, console.log, 123);
Async Await
Generator + Promise
์กฐํฉ์ ์ฌ์ฉํ๋ฉด then
์ ํธ์ถํด์ผ ํ๊ธฐ ๋๋ฌธ์ ์คํ๊ธฐ๊ฐ ํ์ํ๋ค.
ํ์ง๋ง async await
๋ฅผ ์ฌ์ฉํ๋ฉด then
ํธ์ถ์ ๋์ ํด์ค๋ค.
const profile = async function(end, r) {
const userid = await new Promise(res => $.post('member.php', {r}, res));
let added = await new Promise(res => $.post('detail.php', {userid}, res));
added = added.split(",");
end({userid, nick: added[0], thumb: added[1]});
};
profile(console.log, 123);