3

The accepted answer for How do I convert an existing callback API to promises? has this example:

function getUserDataAsync(userId){
    return new Promise(function(resolve,reject){
         getUserData(userId,resolve,reject);
    });
}

Questions:

  1. Shouldn't the body of Promise return something, not just call getUserData (at least in practical code, not as promise demonstration exercise)?

  2. Is this particular Promise also a closure? It seems like it closes over userId, as getUserDataAsync creates and returns a new Promise instance using userId, but I want to be sure.

Community
  • 1
  • 1
LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93
  • 1. No. [The return value is ignored by the `Promise` constructor anyway](http://stackoverflow.com/q/31651610/1048572). 2. Yes, the function expression that is passed to the constructor forms a closure. – Bergi Oct 22 '15 at 08:42

2 Answers2

4

Shouldn't the body of Promise return something, not just call getUserData (at least in practical code, not as promise demonstration exercise)?

No, it doesn't have to. In fact, returning a value from the Promise constructor will have no effect. Only resolve and reject functions can fulfill a Promise.

Is this particular Promise also a closure? It seems like it closes over userId, as getUserDataAsync creates and returns a new Promise instance using userId, but I want to be sure.

Yes, the function passed to the Promise constructor closes over userId.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0
  1. No, it shouldn't return something, because there is nothing to return at that point in time, hence the reason you are using a promise.

  2. Yes.

Jeff
  • 12,085
  • 12
  • 82
  • 152