Before read : 비동기 호출 링크
비동기. 클라이언트와 서버가 있다 했을때, 클라이언트가 요청을 보낸다.
서버는 요청을 받아서 작업을 하고 클라이언트는 요청을 하고 다른 일을 할 수있다.동기적인 task (synchronous) : 단계별로 task를 진행하기 때문에 걸리는 time이 더 걸린다.
비동기적인 task (Asynchronous): 모든 단계를 동시에 진행 할 수 있어 걸리는 time이 줄어든다.
const printString = (string, callback) => {
setTimeout(
() => {
console.log(string)
callback()
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {})
})
})
}
printAll() // A // B // C
const somethingGonnaHappen = callback => {
waitingUntilSomethingHappens()
if (isSomethingGood) {
callback(null, something)
}
}
somethingGonnaHappens((error, data) => {
if (err) {
console.log('ERR!!');
return;
}
return data;
})
const printString = (string) => {
return new Promise((resolve, reject) => {
setTimeout(
() => {
console.log(string)
resolve()
},
Math.floor(Math.random() * 100) + 1
)
})
}
const printAll = () => {
printString("A")
.then(() => {
return printString("B")
})
.then(() => {
return printString("C")
})
}
printAll() // A // B // C
개념 질문 :
1. Promise 실행 함수가 가지고 있는 두 개의 파라미터, resolve, reject는 각각 무엇을 의미하는가?
- resolve()와 reject() 명령어로 다음 task로 넘길 수도, 에러 핸들링도 할 수 있다.
resolve는 주어진 값으로 이행하는 Promise 객체를 반환. .then 메서드가 있는 경우 반환된 promise는 then 메서드를 따라가고 마지막 상태를 취한다. 어떤 값이 프로미스인지 아닌자 알 수 없는 경우, Promis.resolve(value) 후 반환값을 프로미스로 처리할 수 있다.
reject는 주어진 이유로 거부하는 Promise 객체를 반환. reject로 에러처리가 되는 경우에는 .catch()로 에러핸들링을 마지막 체인때 가능하게끔 한다.
- Promise.prototype.then 메서드는 무엇을 리턴?
- 프로미스에 이행 또는 거부 처리기를 추가하고 호출된 처리기의 반환값 또는 프로미스가 처리되지 않은 경우 그 원래 처리된(settled) 값으로 결정하는 새 프로미스를 반환한다.(즉 관련 처리기 onFulfilled 또는 onRejected가 undefined인 경우).
- Promise.prototype.catch 메서드는 무엇을 리턴?
- 프로미스(promise)에 거부 처리기 콜백을 추가하고 호출된 경우 콜백의 반환값 또는 프로미스가 대신 이행된 경우 그 원래 이행(fulfillment)값으로 결정하는(resolving) 새 프로미스를 반환한다.
- Promise의 세가지 상태?
- 대기 (pending), 이행하거나 거부되지 않은 초기 상태
이행 (fulfilled), 연산이 성공적으로 완료됨
거부 (rejected), 연산이 실패함
대기중인 프로미스는 값과 함께 이행할 수도 에러로 인해 거부될 수도 있다.
이때, 프로미스에 연결한 처리기는 그 프로미스의 then 메서드에 의해 대기열에 오른다
function gotoCodestates() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('1. go to codestates') }, 100)
})
}
function sitAndCode() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('2. sit and code') }, 100)
})
}
const result = async() => {
const one = await gotoCodestates();
console.log(one)
const two = await sitAndCode();
console.log(two)
}
result(); // 1. go to codestates // 2. sit and code
- await 키워드 다음에 등장하는 함수 실행은, 어떤 타임을 리턴할 경우에만 의미가 있나?
- await 키워드를 사용할 경우, 어떤 값이 리턴되나?