Promise
- 프로미스는 Promise 생성자 함수를 통해 인스턴스화 한다. 비동기 작업을 수행을 할 resolve와 reject함수를 인자로 전달받는다.
- 비동기 처리가 성공(fulfilled)이면 resolce함수를 호출하고 비동기 처리가 실패(rejected)했으면 reject함수를 호출한다.
const promise = new Promise((resolve, reject) => {
if (true) {
resolve('성공');
} else {
reject('실패');
}
})
promise.then(result => console.log(result))
Promise.all(): 병렬 비동기 처리
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, '1')
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, '2')
})
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 3000, '3')
})
Promise.all([promise1, promise2, promise3])
.then(values => {
console.log(values)
})
//['1', '2', '3']
- Promise.all(): 비동기 처리할 것들이 배열로 담아 Promise.all()에 전달한다
- 위 코드는 3초 뒤에 ['1', '2', '3']을 로그에 찍는다. 병렬 처리이므로 로그에 찍힌 결과는 시간이 아니라 코드가 선언된 순서대로 찍힌다.
- promise.all()은 전달받은 모든 비동기처리가 끝날때 까지 기다렸다가 결과를 한번에 내보낸다.
Promise.all()을 활용하여 한번에 데이터 가져오기
const urls = [
'http://test.com/users',
'http://test.com/posts',
'http://test.com/albums',
]
Promise.all(urls.map(url => {
return fetch(url).then(response => response.json())
})).then(result => console.log(result[0], result[1], result[2])
.catch(()=>console.log('error'))
- catch는 urls에 담긴 3개의 api 호출 중에 하나만 에러나도 코드 실행한다.
- ES6문법을 활용하여 위 코드를 다음과 같이 바꿀 수 있다.
const urls = [
'http://test.com/users',
'http://test.com/posts',
'http://test.com/albums',
]
const getData = async function () {
try{
const [users, posts, albums] = await Promise.all(urls.map(url => {
return fetch(url).then(response => response.json())
console.log(users)
console.log(posts)
console.log(albums)
}catch(err){
console.log('err')
}
}
Promise.finally()
- 비동기 호출이 끝났을 때 실행할 코드를 선언해 줄 수 있다.
- finally 블록 안에 있는 코드는 Promise의 비동기 호출이 성공했거나 실패했던 실행한다.
const urls = [
'http://test.com/users',
'http://test.com/posts',
'http://test.com/albums',
]
Promise.all(urls.map(url => {
return fetch(url).then(response => response.json())
})).then(result => console.log(result[0], result[1], result[2])
.catch(()=>console.log('error'))
.finally(() => console.log(data))
- finally는 Promise에서 어떤 파라미터도 받지 않는다.
for await of
- 반복문으로 비동기 처리를 할 수 있다.
- 반복문에 전달된 모든 비동기문이 모두 마칠 때까지 기다린다.
const urls = [
'http://test.com/users',
'http://test.com/posts',
'http://test.com/albums',
]
const getData = async function () {
const arrayOfPromises = urls.map(urls => fetch(url));
for await (let request of arrayofPromises) {
const data = await request.json();
console.log(data)
}
}
getData()
Promise.all()과 for await of
- Promise.all(): 비동기처리를 동시에 시작한다.
- for await of: 시작하고 끝내고 순차척으로 처리한다.