0

I'm new to promises and trying to wrap my head around something that should be simple. Maybe someone can hit me in the head with it instead!

I've got these two functions:

//an arbitrary method that runs on delay to mimic an async process
    method1 = function( _value, _callback ){
      setTimeout(function(){ 
        console.log('dependency1_resolved');
        _callback.apply(this, [{valIs:_value}]);
      }.bind(this), (Math.random() * 1000));
    };

    //something that can simple return the object
    function returnVal(x){
       console.log(x); //this logs 'Object {valIs: 4}'
       return x;
    }

due to it's async nature, I'd like to run this function in a promise to be used later (maybe even chain later) in my code.

here is my promise:

var promise = new Promise(
  function(resolve, reject) {
    var x = method1(4, returnVal);
    resolve(x);
  }
);

promise.then(function(val) {
  console.log(val); // undefined
  return val;
});
console.log(promise); //Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: undefined}

Does this have anything to do with the .apply method in the first function? What am I missing? Can someone please slap me?

abigwonderful
  • 1,797
  • 1
  • 12
  • 10

2 Answers2

0

Your returnVal callback doesn't actually do anything.

Instead, you need to actually pass a callback that accepts the value:

var promise = new Promise(
  function(resolve, reject) {
    method1(4, function(x) { resolve(x); });
  }
);

You can also just pass resolve itself as the callback:

var promise = new Promise(
  function(resolve, reject) {
    method1(4, resolve);
  }
);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • thank you for including the example. seems so elementary, but that's my level at the moment! Cheers. – abigwonderful Aug 20 '15 at 16:10
  • @abigwonderful: You're welcome! See also http://blog.slaks.net/2015-01-04/async-method-patterns/ & sequels. – SLaks Aug 20 '15 at 16:10
0

Your method1 does return nothing, that's why x is undefined. That the returnVal callback does return something is insignificant, its return value is simply ignored by method1.

You will need to call resolve as the callback to make your code work:

new Promise(
  function(resolve, reject) {
    var x = method1(4, resolve);
  }
).then(function(val) {
  console.log(val); // undefined
  return val;
});

See also How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375