JavaScript - Promise, Generator, and Async/Await

Sync vs. Async
Sync: one after another
Async: one after another, but not necessarily in order

The more complicated the web is, the more asynchronous codes are needed
However, asynchronous does not guarantee the order of works -> functions or developers cannot predict when the works will start and finish.
That was the reason why callback hell happened (to make async functions in order)
Therefore, we should express asynchronous operations synchronously
Let Asynchronous Methods Return Values Like Synchronous Methods
Promise, Generator (ES6), async/await (ES7)
Promise +
.then
A Promise in JavaScript represents a promise to deliver value at some point in the future after an asynchronous operation has been completed.
When a Promise is created using the
newoperator, the callback passed as an argument is executed immediately.If there is a statement that calls the
resolveorrejectfunction inside the callback, the Promise does not move on to the nextthenorcatchblock until one of those functions is called.Therefore, the
resolveorrejectis called only when the asynchronous operation is complete.
new Promise(function (resolve) {
setTimeout(function () {
var name = 'Espresso';
console.log(name);
resolve(name);
}, 500);
}).then(function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var name = prevName + ', Americano';
console.log(name);
resolve(name);
}, 500);
});
}).then(function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var name = prevName + ', Cafe Mocha';
console.log(name);
resolve(name);
}, 500);
});
}).then(function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var name = prevName + ', Cafe Latte';
console.log(name);
resolve(name);
}, 500);
});
});
// refactoring
var addCoffee = (name) => {
return function (prevName) {
return new Promise(function (resolve) {
setTimeout(function () {
var newName = prevName ? `${prevName}, ${name}` : name;
console.log(newName);
resolve(newName);
}, 500);
});
};
};
addCoffee('Espresso')()
.then(addCoffee('Americano'))
.then(addCoffee('Cafe Mocha'))
.then(addCoffee('Cafe Latte'));
Generator (ES6)
Functions marked with an asterisk (*) are generator functions in JavaScript. When a generator function is executed, it returns an iterator object (which has a next() method).
An iterator is an object that can be iterated through using the
next()method. When thenext()method is called, the Generator function starts executing from the beginning until it reaches the firstyieldkeyword, where it stops.When
next()is called again, the function resumes execution from where it left off until it reaches the nextyieldkeyword and stops again.In other words, if you call the
next()method each time an asynchronous operation is completed, the code inside the Generator function will be executedsequentiallyfrom top to bottom.
var addCoffee = function (prevName, name) {
setTimeout(function () {
coffeeMaker.next(prevName ? prevName + ', ' + name : name);
}, 500);
};
var coffeeGenerator = function* () {
var espresso = yield addCoffee('', 'Espresso');
console.log(espresso);
var americano = yield addCoffee(espresso, 'Americano');
console.log(americano);
var mocha = yield addCoffee(americano, 'Cafe Mocha');
console.log(mocha);
var latte = yield addCoffee(mocha, 'Cafe Latte');
console.log(latte);
};
var coffeeMaker = coffeeGenerator();
coffeeMaker.next();
Promise + Async/Await (ES7)
In ES2017, we can use the new async/await syntax to perform asynchronous operations. To use it, we simply add the async keyword before a function that needs to perform asynchronous operations, and then add the await keyword before any statements that require the result of the asynchronous operation.
var addCoffee = function (name) {
return new Promise(function (resolve) {
setTimeout(function(){
resolve(name);
}, 500);
});
};
var coffeeMaker = async function () {
// var coffeeMaker = async () => {
var coffeeList = '';
var _addCoffee = async function (name) {
coffeeList += (coffeeList ? ', ' : '') + await addCoffee(name);
};
// wait until _addCoffee() is done
await _addCoffee('Espresso');
// execute after _addCoffee('Espresso') is done
console.log(coffeeList);
await _addCoffee('Americano');
console.log(coffeeList);
await _addCoffee('Cafe Mocha');
console.log(coffeeList);
await _addCoffee('Cafe Latte');
console.log(coffeeList);
};
coffeeMaker();
![[코테] 그리디 문제 - 무지의 먹방 라이브](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1712215455263%2F1ac1f35a-8862-4e42-8d0c-e2bea01e04c0.png&w=3840&q=75)
![[코테] Bfs 토마토](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709032619170%2F70056896-c857-444b-9c99-45bfcb466806.png&w=3840&q=75)
![[코테] Dfs 문제 유형 - 그래프 내에서 구분하여 카운트 하기](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1709019361383%2Fb0585d72-c808-4169-83a9-2724f312e927.png&w=3840&q=75)
![[코테] DFS vs BFS](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971211123%2F71f9386c-6a62-43b2-a602-4d084c24d6cf.png&w=3840&q=75)
![[코테] 여행경로](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1708971251412%2F27ce72ed-8ee7-4d13-a02f-ff4bbe50c4be.png&w=3840&q=75)