Skip to content

Instantly share code, notes, and snippets.

@hoetmaaiers
Last active February 23, 2016 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoetmaaiers/1834e101e54b36083690 to your computer and use it in GitHub Desktop.
Save hoetmaaiers/1834e101e54b36083690 to your computer and use it in GitHub Desktop.
Promise solution

Promise solution

/**
 * HANDSON Promises: provide more levels to the game
 *
 * We have some cool levels waiting for you at the following urls:
 * - 'http://localhost:8080/levels/basic.json'
 * - 'http://localhost:8080/levels/easy-start.json'
 * - 'http://localhost:8080/levels/hard-to-get-drunk.json'
 *
 * Fetch these levels through fetch. Good to know that fetch returns a promise.
 * In the end you need ta have an array of all the fetched levels.
 * These levels can be passed to the game.
 *
 *     fetch(url)
 *       .then((response) => {
 *         if (response.status >= 400) {
 *           throw new Error("Bad response from server");
 *         }
 *         return response.json();
 *       }).then((level) => {
 *         return level;
 *       });
 */

 const urls = [
   'basic',
   'easy-start',
   'hard-to-get-drunk',
 ];

getLevels(urls)
.then((levels) => {
  const game = new Game();
  game.run(levels, DOMDisplay);
});



/**
 * getLevels
 * @param {array} levelNames
 * @return {promise array} levelNames
 */
function getLevels(levelNames) {
  let allLevels = levelNames.map((level) => {
    return getLevel(level);
  });

  return Promise.all(allLevels);
}


/**
 * getLevel
 * @param {string} levelName
 */

function getLevel(levelName) {
  let levelUrl = `http://localhost:8080/levels/${levelName}.json`;

  return fetch(levelUrl)
    .then((response) => {
      if (response.status >= 400) {
                throw new Error("Bad response from server");
            }
            return response.json();
    }).then((map) => {
      return map;
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment