10

I'm trying to execute the following code:

exports.myFunction = function(){
    myPromise.doThis().then(ret => {
     return ret;
    });
}

When calling this function it returns undefined. How do I make the function wait for the promise to resolve then return.

Simar
  • 2,475
  • 5
  • 16
  • 19
  • you can't. you can only give it a callback itself, and call that callback from within the `then` call, or you return another promise – Christian Fritz May 13 '16 at 02:51
  • 1
    In Javascript, you cannot "wait" for an async operation to finish before returning from your function. It simply does not work that way. Instead, you return the promise and let the caller use `.then()` on it to know when the result is ready. – jfriend00 May 13 '16 at 02:57
  • 1
    BTW, `.then(ret => { return ret; });` is (almost) a no-op. –  May 13 '16 at 04:31
  • See also http://stackoverflow.com/questions/34959257/why-isnt-my-future-value-available-now/34959258#34959258. –  May 13 '16 at 04:37

1 Answers1

12

Being asynchronous, there is no guarantee of knowing when the promise will be resolved. It may have to wait for a while (depending on what you are doing).

The typical way of continuing execution after a promise is by chaining execution or by using callback functions.

As a Callback

Your sample code (to me) suggests the use of a callback.

exports.myFunction = function(callback){
    myPromise.doThis().then(ret => {
        callback(ret);
    });
}

Then using would look similar to:

var myFunction = require('pathToFile').myFunction;

myFunction(function(ret){
    //Do what's required with ret here
});

Edit:

As @torazaburo mentioned, the function can be condensed into:

exports.myFunction = function(callback){
    myPromise.doThis().then(callback);
} 

As a Promise

exports.myFunction = function(){
    //Returnes a promise
    return myPromise.doThis();
}

Then using would look similar to:

var myFunction = require('pathToFile').myFunction;

myFunction().then(function(ret){
    //Do what's required with ret here
});
AXRS
  • 154
  • 1
  • 6
  • 2
    *resolved completely* Promises do not resolve a little bit. They either are not resolved, or are resolved. Also, your mixture of promises and callbacks is quite odd. BTW, to say `.then(ret => { callback(ret); })` (why the unnecessary curly brackets?) is (almost) identical to saying `.then(callback)`. But why write a function whose only purpose is to make an asynchronous call and hang a `then` from it invoking a specified callback? Instead, let the caller specify the `then` themselves. –  May 13 '16 at 04:35
  • 1
    This is true, they are either resolved or not. I will revise my response to remove this for clarity. You can also use the `callback` function as a direct replacement, removing the unnecessary assignment of `ret`. I deliberately opted for the verbose method as an example. Condensed notation can often leave new developers perplexed. – AXRS May 13 '16 at 06:08