Promise
function delay(sec, callback) {
setTimeout(() => {
callback(new Date().toISOString());
}, sec * 1000);
}
console.log("start", new Date().toISOString()); // 'start' '2021-06-25T16:02:24.522Z'
// 위에 콘솔이 먼저 나오고 아래 콘솔 새개가 동시에 출력
delay(1, (result) => {
console.log(1, result); // 1 '2021-06-25T16:02:25.526Z'
});
delay(1, (result) => {
console.log(1, result); // 1 '2021-06-25T16:02:25.526Z'
});
delay(1, (result) => {
console.log(1, result); // 1 '2021-06-25T16:02:25.526Z'
});
// 1초 간격으로 출력이 된다. => 복잡해지면 가독성이 떨어짐(Promise / async await의 필요)
delay(1, (result) => {
console.log(1, result);
delay(1, (result) => {
console.log(1, result);
delay(1, (result) => {
console.log(1, result);
});
});
});
//Promise
function delayP(sec) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(new Date().toISOString());
}, sec * 1000);
});
}
delayP(1).then((result) => {
console.log(1, result); // 1 '2021-06-25T16:02:25.526Z'
});
// 1초 간격으로 출력이 된다.
delayP(1)
.then((result) => {
console.log(1, result); // 1 '2021-06-25T16:02:25.526Z'
return delayP(1);
})
.then((result) => {
console.log(2, result); // 2 '2021-06-25T16:02:25.526Z'
return delayP(1);
})
.then((result) => {
console.log(3, result); // 3 '2021-06-25T16:02:25.526Z'
})
.then((result) => {
console.log(result); // undefined (위에 then에서 아무것도 리턴하지 않아서)
});
Async / Await
function delayP(sec) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(new Date().toISOString());
}, sec * 1000);
});
}
// async(그 함수를 Promise로 리턴하는 함수로 만들어 줌)
async function myAsync() {
return "async";
}
myAsync().then((result) => {
console.log(result); // 'async'
});
async function myAsync() {
// 일반 함수 리턴값을 받아서 사용 가능
// const result = await delayP(3).then((time) => {
// return "x";
// });
// console.log(result);
// return "async";
await delayP(3); // await을 하는 동안 return을 하지 않음
return "async";
}
myAsync().then((result) => {
console.log(result); // 'async'
});
Callback
function fakeSetTimeout(callback, delay) {
callback();
}
// fake callback(동기적)
// 0 hello 1 순으로 출력
console.log(0);
fakeSetTimeout(function () {
console.log("hello");
}, 0);
console.log(1);
// callbaack(비동기적)
// 0 1 hello 순으로 출력
console.log(0);
SetTimeout(function () {
console.log("hello");
}, 0);
console.log(1);