Return from a promise then()

Priscy picture Priscy · Dec 4, 2015 · Viewed 178.1k times · Source

I have got a javascript code like this:

function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}

var test = justTesting();

I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?

Answer

c0ming picture c0ming · Apr 1, 2017

When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

Source: https://developers.google.com/web/fundamentals/getting-started/primers/promises#queuing-asynchronous-actions