setTimeout()
예시
function testSetTimeout(callback) {
console.log("1. Before callback");
setTimeout(function () {
console.log("2. callback function");
if (typeof callback === "function") {
callback();
} else {
console.log(" Callback is not func!");
}
}, 3000);
console.log("3. After callback");
}
(function runA() {
testSetTimeout(function () {
console.log(" Call about setTimeout callback func!!");
});
})();
결과
1. Before callback
3. After callback
2. callback function
Call about setTimeout callback func!!
Promise
예시
function testPromise(callback) {
return new Promise(function(resolve, reject) {
if (typeof callback === "function") {
console.log("1. callback is function.");
setTimeout(() => {
console.log("2초 흐름");
resolve(callback);
}, 2000);
} else {
reject("2. callback is not a function.");
}
});
}
(function run() {
testPromise(function() {
console.log("2. callback function!");
})
.then(function(callback) {
callback();
})
.then(function() {
console.log("3. callback is done.");
})
.catch(function(reason) {
console.error(reason);
});
})();
결과
1. callback is function.
2초 흐름
2. callback function!
3. callback is done.
Async / Await
예시
function testPromise(callback) {
return new Promise((resolve, reject) => {
if (typeof callback === "function") {
console.log("1. callback is function.");
setTimeout(() => {
resolve(callback);
}, 2000);
} else if (typeof callback === "number") {
console.log("1. callback number is " + callback);
setTimeout(() => {
resolve(callback);
}, 2000);
} else {
reject("1. callback is not a function, number");
}
});
}
async function testAsync(x) {
var a = testPromise(20)
var b = testPromise(30)
return x + await a + await b
}
testAsync(50).then(result => console.log(result))
결과
1. callback number is 20
2. callback number is 30
100
setTimeout과는 다르게, promise와 async는 명확히 앞서 하던 일들이 끝나면 다음 일을 할 수 있도록 명시해준다.
Reference
https://jicjjang.github.io/2017/02/05/promise-and-async-await/
'JavaScript' 카테고리의 다른 글
arrow function (0) | 2019.08.19 |
---|---|
구조분해할당 (0) | 2019.08.19 |
클로저 (0) | 2019.07.24 |
JSON (0) | 2019.07.23 |
async await (0) | 2019.07.23 |