async

    await와 then 함께쓰기?

    Promise를 처리하기 위해서 then으로 체이닝을 하거나 async/await 함수를 활용할 수 있다. 그런데, 이 둘이 함께 쓰인 코드를 보았다. 재현해보자면, 다음과 같다. const { default: axios } = require("axios"); const sampleFn = async () => { try { const result = await axios.get("https://jsonplaceholder.typicode.com/todos/1") .then(el => { console.log("then", el.data); return el.data; }) .catch(err => console.error("then", err)); console.log('await', result); ..

    syntactic sugar in Javascript (Class와 Async Await)

    자바스크립트에서는 syntactic sugar라는 개념이 있는데, 이는 코드 작성을 더 간결하고 쉽게 만들어주는 문법적 편의 기능을 의미한다. 이를 잘 활용하면 쉽고 잘 읽히는 코드를 작성할 수 있다. Class class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, I'm ${this.name}.`); } } 프로토타입 생성자 함수 function Person(name, age) { this.name = name; this.age = age; } Person.prototype.sayHello = function() { console.log(`Hello, I'm ${..

    자바스크립트(javascript) 비동기, 동기 - Promise, Callback, async, await

    자바스크립트는 비동기로 작동한다. 하지만 웹 페이지의 로딩을 기다리거나, 입력을 기다리거나, 다운로드가 완료된 후에 실행되야 하는 코드가 있을 수 있다. 따라서 이때는 동기적으로 작동이 될 수 있도록 한다. // 비동기 const printHi = () => { setTimeout(() => { console.log("안녕!") }, Math.random() * 100); } const printWhat = () =>{ setTimeout(() => { console.log("우리 뭐할까?"); }, Math.random() * 100); } const printBye = () => { setTimeout(() => { console.log("잘가!") }, Math.random() * 100); } p..

    forEach와 async await (for of 사용하기)

    🥝 forEach는 promises를 기다리지 않기에 async await 구문 역시 동작하지 않는다. const setTimeoutPlus = (num1, num2) => { return new Promise((resolve, reject) => { try { setTimeout(() => { resolve(num1 + num2); }, 3000); } catch (e) { reject("ERROR", e); } }) } const asyncForEachFuc = (data) => { let tmp = []; console.log("start", tmp); data.forEach(async function(element,index,array){ tmp.push(await setTimeoutPlus(el..