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);