## If you're using promises, this answer is for you.

This means AngularJS, jQuery (with deferred), native [XHR][1]'s replacement (fetch), [Ember.js][2], [Backbone.js][3]'s save or any [Node.js][4] library that returns promises.

Your code should be something along the lines of this:

    function foo() {
        var data;
        // Or $.get(...).then, or request(...).then, or query(...).then
        fetch("/echo/json").then(function(response){
            data = response.json();
        });
        return data;
    }

    var result = foo(); // 'result' is always undefined no matter what.

Felix Kling did a fine job writing an answer for people using jQuery with callbacks for Ajax. I have an answer for native XHR. This answer is for generic usage of promises either on the frontend or backend.


---------------
## The core issue

The JavaScript concurrency model in the browser and on the server with Node.js/io.js is _asynchronous_ and _reactive_.

Whenever you call a method that returns a promise, the `then` handlers are _always_ executed asynchronously - that is, __after__ the code below them that is not in a `.then` handler.

This means when you're returning `data` the `then` handler you've defined did not execute yet. This in turn means that the value you're returning has not been set to the correct value in time.

Here is a simple analogy for the issue:

<!-- begin snippet: js hide: false -->

<!-- language: lang-js -->

        function getFive(){
            var data;
            setTimeout(function(){ // Set a timer for one second in the future
               data = 5; // After a second, do this
            }, 1000);
            return data;
        }
        document.body.innerHTML = getFive(); // `undefined` here and not 5

<!-- end snippet -->

The value of `data` is `undefined` since the `data = 5` part has not executed yet. It will likely execute in a second, but by that time it is irrelevant to the returned value.

Since the operation did not happen yet (Ajax, server call, I/O, and timer) you're returning the value before the request got the chance to tell your code what that value is.

One possible solution to this problem is to code _re-actively_, telling your program what to do when the calculation completed. Promises actively enable this by being temporal (time-sensitive) in nature.

### Quick recap on promises

A Promise is a _value over time_. Promises have state. They start as pending with no value and can settle to:

 - __fulfilled__ meaning that the computation completed successfully.
 - __rejected__ meaning that the computation failed.

A promise can only change states _once_ after which it will always stay at the same state forever. You can attach `then` handlers to promises to extract their value and handle errors. `then` handlers allow [chaining][5] of calls. Promises are created by [using APIs that return them][6]. For example, the more modern Ajax replacement `fetch` or jQuery's `$.get` return promises.

When we call `.then` on a promise and _return_ something from it - we get a promise for _the processed value_. If we return another promise we'll get amazing things, but let's hold our horses.

### With promises

Let's see how we can solve the above issue with promises. First, let's demonstrate our understanding of promise states from above by using the [Promise constructor][7] for creating a delay function:

    function delay(ms){ // Takes amount of milliseconds
        // Returns a new promise
        return new Promise(function(resolve, reject){
            setTimeout(function(){ // When the time is up,
                resolve(); // change the promise to the fulfilled state
            }, ms);
        });
    }

Now, after we [converted setTimeout][8] to use promises, we can use `then` to make it count:

<!-- begin snippet: js hide: false -->

<!-- language: lang-js -->

    function delay(ms){ // Takes amount of milliseconds
      // Returns a new promise
      return new Promise(function(resolve, reject){
        setTimeout(function(){ // When the time is up,
          resolve(); // change the promise to the fulfilled state
        }, ms);
      });
    }

    function getFive(){
      // We're RETURNING the promise. Remember, a promise is a wrapper over our value
      return delay(100).then(function(){ // When the promise is ready,
          return 5; // return the value 5. Promises are all about return values
      })
    }
    // We _have_ to wrap it like this in the call site, and we can't access the plain value
    getFive().then(function(five){
       document.body.innerHTML = five;
    });

<!-- end snippet -->

Basically, instead of returning a _value_ which we can't do because of the concurrency model - we're returning a _wrapper_ for a value that we can _unwrap_ with `then`. It's like a box you can open with `then`.

### Applying this

This stands the same for your original API call, you can:

    function foo() {
        // RETURN the promise
        return fetch("/echo/json").then(function(response){
            return response.json(); // Process it inside the `then`
        });
    }

    foo().then(function(response){
        // Access the value inside the `then`
    })

So this works just as well. We've learned we can't return values from already asynchronous calls, but we can use promises and chain them to perform processing. We now know how to return the response from an asynchronous call.

## ES2015 (ES6)

ES6 introduces [generators][9] which are functions that can return in the middle and then resume the point they were at. This is typically useful for sequences, for example:

    function* foo(){ // Notice the star. This is ES6, so new browsers, Nodes.js, and io.js only
        yield 1;
        yield 2;
        while(true) yield 3;
    }

Is a function that returns an _iterator_ over the sequence `1,2,3,3,3,3,....` which can be iterated. While this is interesting on its own and opens room for a lot of possibility, there is one particular interesting case.

If the sequence we're producing is a sequence of actions rather than numbers - we can pause the function whenever an action is yielded and wait for it before we resume the function. So instead of a sequence of numbers, we need a sequence of _future_ values - that is: promises.

This somewhat a tricky, but very powerful trick let’s us write asynchronous code in a synchronous manner. There are several "runners" that do this for you. Writing one is a short few lines of code, but it is beyond the scope of this answer. I'll be using Bluebird's `Promise.coroutine` here, but there are other wrappers like `co` or `Q.async`.

    var foo = coroutine(function*(){
        var data = yield fetch("/echo/json"); // Notice the yield
        // The code here only executes _after_ the request is done
        return data.json(); // 'data' is defined
    });

This method returns a promise itself, which we can consume from other coroutines. For example:

    var main = coroutine(function*(){
       var bar = yield foo(); // Wait our earlier coroutine. It returns a promise
       // The server call is done here, and the code below executes when done
       var baz = yield fetch("/api/users/" + bar.userid); // Depends on foo's result
       console.log(baz); // Runs after both requests are done
    });
    main();

## ES2016 (ES7)

In ES7, this is further standardized. There are several proposals right now, but in all of them you can `await` promise. This is just "sugar" (nicer syntax) for the ES6 proposal above by adding the `async` and `await` keywords. Making the above example:

    async function foo(){
        var data = await fetch("/echo/json"); // Notice the await
        // code here only executes _after_ the request is done
        return data.json(); // 'data' is defined
    }

It still returns a promise just the same :)

  [1]: https://en.wikipedia.org/wiki/XMLHttpRequest
  [2]: https://en.wikipedia.org/wiki/Ember.js
  [3]: https://en.wikipedia.org/wiki/Backbone.js
  [4]: https://en.wikipedia.org/wiki/Node.js
  [5]: https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks
  [6]: https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises
  [7]: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise
  [8]: http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises
  [9]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*