비동기작업을 제어하기위해 나온개념.
콜백지옥에서 어느정도 벗어나게 해준다.
const promise = new Promise((resolve, reject)) => {
//작업 성공하면 resolve호출, 실패면 reject호출.
)}
기본 틀은 이런식이다.
응용은 보통 이렇게 한다.
const myPromise = new Promise((resolve, reject)) => {
//...api콜
resove("success!");
})
myPromise.then((text) => {
console.log("hi" + text)
})
Promise
의 장점은 들여쓰기가 사라진다는 것이다.
myPromise.then((result) => {
return nextPromise(result)
}).then((result) => {
return nextnextPromise(result)
}).then ....
에러는 try-catch
문의 catch
로 잡는다
...then(result => ...).catch(e => console.log(e))
마지막에 finally
를 호출하면 성공-실패 여부에 상관없이 호출할수있다.
..catch(e => console.log(e)).finally(() => console.log("dammm");
Promise.all
: 여러 Promise
가 호출되고 난 후에 호출되는 콜백이다.Promise.all([promise1, promise2, promise3]).then(() => ...)
Promise.race
: 하나라도 resolve, reject
되면 종료Promise.race([promise1, promise2, promise3]).then(() => ...)
Promise.any
: 하나라도 resolve
되면 종료Promise.any([promise1, promise2, promise3]).then(() => ...)
Promise.allSettled
: 모두 이행되고 호출Promise.allSettled([promise1, promise2, promise3]).then(() => ...)
Promise.resolve
: 주어진 값으로 이행하는 Promise.then
객체 생성.Promise
로 한번 래핑해서 준다. const findMember = (name) => {
if(cached[name]){
return Promise.resolve(cached[name])
}
return //api콜
}
findMember('kim').then((member) => ...)
이렇게 Promise
가 아닌 곳에서도 Promise
처럼 값을 줄 수 있기에, 밖에서 분기처리를 하지 않아도 됨.
Promise
가 들여쓰기 지옥을 줄여주지만, 체이닝은 여전히 존재한다.
보기 힘든건 마찬가지!
또한 읽는 순서와 코드 실행순서가 다르기에 헷갈릴수 있다.
이를 해결하기위해 나온것이 async, await
.
참고로 async
로 감싼 함수의 결과는 Promise
로 래핑된다.
비동시 http 요청을 편리하게 만들어줌.
XMLHttprequest
의 진화버전!
Promise
기반으로 동작한다.
fetch(url).then((result.json())...)
응답 기본 결과는 Response객체다. json()
이나 text()
로 파싱이 필요함.
Http error(404, 500등..)이 발생해도 reject
되지 않는다.
=> 한번 더 체크가 필요하다. status code, ok
등...
"files.insertFinalNewline": true
추가.