프로미스란
프로미스와 async await
Promise 이기만 하면 우리는 기다릴(await) 수 있어요.
setState는 비동기다
이전 state값을 기준으로 새로운 state를 업데이트를 하려면 setState() 안에 함수를 넣어라
Promise 반환하기 ****** 이거 읽으면 promise, async, await 통합이해 완료
const add10 = (num) => { return num + 10 } console.log(add10(5)) // 15 // ------- const add5 = async (num) => num + 5; //async 함수 만들어서 add5에 담음 console.log(add5(5)) // Promise {<resolved>: 10} //함수 호출, 결과는 Promise 반환됨
The only difference between the above 2 functions is the async keyword. Async wraps the return value in the promise
이렇게 Promise 안쓰고 async 함수 만들어서 담고, 암대나 불러서 써도 됨.
//함수생성 const processDataAsycn = async (num) => { if(typeof num === 'number') { return 2*num; } else { throw new Error('Something went wrong'); } }; //Promise반환된다는 걸 이용해서 동기방식으로 처리 processDataAsycn(21).then((data) => { console.log('Data from processDataAsycn() with async( When promise gets resolved ): ' + data); }).catch((error) => { console.log('Error from processDataAsycn() with async( When promise gets rejected ): ' + error); });
얘도 마찬가지로 async함수 만들어서 const processDataAsync 에 담아서 썼음.