-
[JS] async/awaitDev/JS 2018. 4. 4. 23:40
async/await 에 대하여
1. async
Async 함수가 호출되면 이 함수는 Promise 를 반환한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersasync function add1() { ... } add1().then(value => { console.log(value) }) 그리하여 위와 같이 add1을 호출하였을 때 Promise가 반환되어 .then() 함수 호출이 가능한 것이다.
다른 비동기 처리방식 중 setTimeout과 다르게 async는 명확하게 앞에서 하던 일이 끝나면 다음일을 할 수 있게 명시해준다.
2. await
await는 async 문 안에서만 사용될 수 있다..
또한 await 문은 async 함수의 실행을 중단시키고, Promise가 fulfill(이행) 또는 reject(거절) 되기 전까지 기다린다.
그리고 나서 다시 async 함수를 실행시킵니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters//async await function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(()=> { resolve(x); //결정되는 promise 값, 즉 x 반환 }, 2000); }); } async function add1(x) { var a = resolveAfter2Seconds(20); var b = resolveAfter2Seconds(30); return x + await a + await b; //await 는 async문 실행 중지 시키고, promise에서 fulfill 된 값이 있을때까지 기다리는것 } add1(10).then(v => { console.log(v); }) //async 함수가 호출되면 promise를 반환하여 .then이 가능 async function add2(x) { var a = await resolveAfter2Seconds(20); var b = await resolveAfter2Seconds(30); return x + a + b; } add2(10).then(v => { console.log(v); }) 'Dev > JS' 카테고리의 다른 글
[JS] Javascript Propagation :: 이벤트 버블링, 이벤트 타겟, 이벤트 캡쳐 (0) 2018.05.21 [JS]react-router 적용해보기 (0) 2018.05.21 [JS] ECMA2018 : ES9 알아보기 (0) 2018.04.28 [JS] Redux Thunk 알아보기 (0) 2018.04.28 [JS] 테스트 프레임워크 Mocha.js 시작하기 (0) 2018.04.22