비동기 프로그래밍: 콜백, 약속 및 Async/Await

Feb 28 2023
.

function getData(callback) {
  // make an API call to get data
  // when the data is ready, call the callback function
  callback(data);
}

getData(function(data) {
  // do something with the data
});

function getData() {
  return new Promise(function(resolve, reject) {
    // make an API call to get data
    // when the data is ready, call resolve with the data
    // if there's an error, call reject with the error message
  });
}

getData().then(function(data) {
  // do something with the data
}).catch(function(error) {
  // handle the error
});

async function getData() {
  // make an API call to get data
  // when the data is ready, return it
  // if there's an error, throw an exception
}

async function main() {
  try {
    const data = await getData();
    // do something with the data
  } catch (error) {
    // handle the error
  }
}

main();