Callback hell 탈출기

C

callback hell

function callBacks(title, done) {
  API.MovieList(title, function(movieList) {
    const ids = movieList.map((movie) => movie.id);
    API.MovieRatings(ids, function(movieRatings) {
      const uids = movieRatings.map((rt) => rt.userId);
      API.UserProfiles(uids, function(userProfiles) {
        done(movieList, ratingIds, userProfiles);
      });
    });
  });
}

API 디자인

const API = {
  MovieList: (title) => {
    return new Promise((resolve, reject) => {
      try {
        const movieList = get_data_from_server(title);
        resolve(movieList);
      } catch (err) {
        reject(err);
      }
    });
  },
  MovieRatings: (movieIds) => {
    return new Promise((resolve, reject) => {
      try {
        const movieRatings = get_data_from_server(movieIds);
        resolve(movieRatings);
      } catch (err) {
        reject(err);
      }
    });
  },
  UserProfiles: (uids) => {
    return new Promise((resolve, reject) => {
      try {
        const userProfiles = get_data_from_server(uids);
        resolve(userProfiles);
      } catch (err) {
        reject(err);
      }
    });
  },
}

Promise로 탈출

// Promise Version
function callbacks(done) {
  const results = [];
  API.MovieList("love")
    .then(movieList => {
      results.push(movieList);
      return API.MovieRatings(movieList);
    })
    .then(movieRatings => {
      results.push(movieRatings);
      return API.UserProfiles(movieRatings);
    })
    .then(userProfiles => {
      results.push(userProfiles);
      done(results);
    })
    .catch(err => {
      console.log(err);
    });
}


callbacks((arr) => {
  console.log(arr);
});

async/await로 탈출

async function callbacks2(done) {
  try {
    let movieList = await API.MovieList("love");
    let movieRatings = await API.MovieRatings(movieList);
    let userProfiles = await API.UserProfiles(movieRatings);
    done([movieList, movieRatings, userProfiles]);
  } catch (err) {
    console.log(err);
  }
}

callbacks2((arr) => {
  console.log(arr);
});

Add Comment