Javascript: How to return the response from an asynchronous call

While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.

There are three different solutions that are all building on top of each other:

  1. Promises with async/await (ES2017+, available in older browsers if you use a transpiler or regenerator)
  2. Promises with then() (ES2015+, available in older browsers if you use one of the many promise libraries)
  3. Callbacks (aka Callback Hell, not recommended )

function getGithubRepository() {
  return new Promise(function (resolve, reject) {
    $.ajax({
      method: "get",
      url: "https://api.github.com/repos/ricardodantas/heroku-scripts"
    })
      .done(function (response) {
        resolve(response);
      })
      .fail(function (error) {
        reject(error);
      });
  });
}

// Promise with then()
getGithubRepository()
  .then(function (result) {
    console.log("Then: Repo name: ", result.name);
  })
  .catch(function (error) {
    console.error(error.statusText);
  });

// Promises with async/await
(async () => {
  try {
    const result = await getGithubRepository();
    console.log("Async/Await Repo name: ", result.name);
  } catch (err) {
    console.log(err);
  }
})();