javascript 는 비동기 함수 언어이다.
💡 비동기란 ?비동기 예제 (https://kkhcode.tistory.com/6)
Promise (약속)
Javascript 의 비동기 성격을 동기 성격으로 사용할 수 있는 방법이다.
const promise = function () {
return new Promise(function (resolve, reject) {
const a = 1
// 3초 후에 실행됨
setTimeout(function () {
if (a === 1) {
resolve("success")
} else {
reject(new Error("a is not 5"))
}
}, 3000)
})
}
// Promise 의 기본형태
promise()
.then(/* resolve일 때*/)
.then()
.then()
.then()
...
.catch(/* reject일 때 */)
/* then을 벗어나면 비동기의 영역이 된다. */
// async/await 를 같이쓸때
async function run () {
try {
await promise()
console.log("3s later...")
/* 동기 영역 */
} catch (err) {
console.log(err)
}
}
run()
async/await
ES7 에서 채택되어 나온 Javascript 내장 키워드 이다. Promise랑 함께 사용 가능하다.
axios, fetch 와도 함께 사용 가능하다.
ES6에서 promise가 도입되었다. 그 전에는 주로 콜백 함수를 다른 인자로 넘겨서 비동기 처리를 했다.
a(1, function(){ })
function a() { }
두 번째 인자로 콜백 함수가 넘어간다 → 함수 안에서 인자로 넘어온 콜백 함수가 호출된다.
⇒ 연쇄 호출하는 경우 “콜백 지옥”에 빠진다
이때 promise을 사용한다.