๐ง async / await
async/await๋ ์๋ฐ์คํฌ๋ฆฝํธ์ ๋น๋๊ธฐ ์ฒ๋ฆฌ ํจํด ์ค
๊ฐ์ฅ ์ต๊ทผ์ ๋์จ ๋ฌธ๋ฒ์ด๋ค. ๊ธฐ์กด์ ๋น๋๊ธฐ ์ฒ๋ฆฌ ๋ฐฉ์์ธ ์ฝ๋ฐฑํจ์์ ํ๋ก๋ฏธ์ค์ ๋จ์ ์ ๋ณด์ํ๊ณ , ๊ฐ๋ฐ์๊ฐ ์ฝ๊ธฐ ์ข์ ์ฝ๋๋ฅผ ์์ฑํ ์ ์๊ฒ ๋์์ค๋ค
๐ง ๋น๋๊ธฐ ์ฒ๋ฆฌ๋?
setTimeout(
function (name) {
var coffeeList = name;
console.log(coffeeList);
setTimeout(
function (name) {
coffeeList += ", " + name;
console.log(coffeeList);
setTimeout(
function (name) {
coffeeList += ", " + name;
console.log(coffeeList);
setTimeout(
function (name) {
coffeeList += ", " + name;
console.log(coffeeList);
},
500,
"์นดํ๋ผ๋ผ"
);
},
500,
"์นดํ๋ชจ์นด"
);
},
500,
"์๋ฉ๋ฆฌ์นด๋
ธ"
);
},
500,
"์์คํ๋ ์"
);
์ฝ๋ฐฑํจ์๊ฐ ๊ธธ์ด์ง ์๋ก ๊ฐ๋ ์ฑ์ด ์ ์ ๋จ์ด์ง๋ค.
new Promise(function (resolve) {
setTimeout(function () {
var name = '์์คํ๋ ์';
console.log(name);
resolve(name);
}, 500);
}).then(function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var name = prevName + ', ์๋ฉ๋ฆฌ์นด๋
ธ';
console.log(name);
resolve(name);
}, 500);
});
}).then(function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var name = prevName + ', ์นดํ๋ชจ์นด';
console.log(name);
resolve(name);
}, 500);
});
}).then(function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var name = prevName + ', ์นดํ๋ผ๋ผ';
console.log(name);
resolve(name);
}, 500);
});
});
Promise๊ฐ ์ฐ๊ฒฐ๋๋ฉด์ then ๋ถ๋ถ์ด ๊ณ์ ๋ฐ๋ณต.. ์ฝ๋์ ๊ฐ๋
์ฑ์ด ์ ์ ๋จ์ด์ง๋ ๋จ์
์ด๋ฅผ ๋ณด์ํ๊ธฐ ์ํด ๋น๋๊ธฐ๋ฅผ ์ฒ๋ฆฌํ๋ ์ต์ ๋ฌธ๋ฒ์ธ async / await๊ฐ ๋ฑ์ฅ
var addCoffee = function (name) {
return new Promise(function (resolve) {
setTimeout(function(){
resolve(name);
}, 500);
});
};
var coffeeMaker = async function () {
var coffeeList = '';
var _addCoffee = async function (name) {
coffeeList += (coffeeList ? ', ' : '') + await addCoffee(name);
};
await _addCoffee('์์คํ๋ ์');
console.log(coffeeList);
await _addCoffee('์๋ฉ๋ฆฌ์นด๋
ธ');
console.log(coffeeList);
await _addCoffee('์นดํ๋ชจ์นด');
console.log(coffeeList);
await _addCoffee('์นดํ๋ผ๋ผ');
console.log(coffeeList);
};
coffeeMaker();