내일부터 react-native 프로젝트 기간이고 기간은 일주일이다.
프로젝트 하기 앞서서 오랜만에 비동기작업을 할 수 있게 해주는 Promise 객체
에 대해서 이해하고 시작할 예정이다.
promise
를 좀더 편하게 사용하기 위해 async
와 await
을 사용한다.
async
는 function 앞에 위치한다.
async
가 붙은 함수는 반드시 프라미스를 반환한다.
await
은 프라미스가 처리될 때 까지 기다려준다.
test(); // 1. 함수 호출
function a() {
return new Promise(function (resolve) {
// new Promise 객체 생성
setTimeout(() => {
console.log("A");
resolve(); //resolve 호출
}, 1000);
});
}
function b() {
console.log("B");
}
async function test() {
// 함수앞에 async 표기
await a(); // await 을 활용해 resolve가 호출 될때까지 값을 먼저 실행
b();
}
1초뒤에 A와 B가 동시에 출력.
function a () {
return new Promise(function (resolve) {
setTimeout(() => {
console.log('A')
resolve()
}, 1000)
})
}
function b () {
return new Promise(function (resolve) {
setTimeout(() => {
console.log('B')
resolve()
}, 1000)
})
}
function c () {
return new Promise(function (resolve) {
setTimeout(() => {
console.log('C')
resolve()
}, 1000)
})
}
function d () {
return new Promise(function (resolve) {
setTimeout(() => {
console.log('D')
resolve()
}, 1000)
})
}
async function test() {
await a()
await b()
await c()
await d()
console.log('done')
}
test()
A,B,C,D 가 1초마다 순차적으로 출력 됨
function a(number) {
return new Promise((resolve, reject) => { // Promise 객체에서는 매개변수로 resolve,reject를 선언한다.
if (number > 4) { // 4는 8보다 크므로 reject 실행 , 만약 거짓이면 무시
reject();
return;
}
setTimeout(() => { // 거짓일시, 1초 후에 'A'와 'resolve!'가 출력됨.
console.log("A");
resolve();
}, 1000);
});
}
async function test() {
try {
await a(8); // 인자값 8인 인자를 전달
console.log("Resolve!");
} catch (error) {
console.log("reject"); // reject 출력 됨
}
}
test();
[참고자료]