./categories/front-end
JS Callback·Promise·async/await
| Callback | Promise | async/await | |
|---|---|---|---|
| 형태 | 함수 인자 | then/catch 체인 | 동기 스타일 |
| 에러 | err-first 콜백 | .catch() | try/catch |
| 단점 | 콜백 지옥 | 체인 길어지면 복잡 | — |
Callback
function getData(cb) {
setTimeout(() => cb(null, "data"), 1000);
}
getData((err, data) => console.log(data));
Promise
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("data"), 1000);
});
}
getData().then(console.log).catch(console.error);
async/await
async function run() {
try {
const data = await getData();
console.log(data);
} catch (e) {
console.error(e);
}
}
병렬
const [a, b] = await Promise.all([getA(), getB()]);
./comments