91

I have a javascript function where I want to return the value that I get after the return method. Easier to see than explain

function getValue(file){
    var val;
    lookupValue(file).then(function(res){
       val = res.val;
    }
    return val;
}

What is the best way to do this with a promise. As I understand it, the return val will return before the lookupValue has done it's then, but the I can't return res.val as that is only returning from the inner function.

pedalpete
  • 21,076
  • 45
  • 128
  • 239
  • @OneKitten, the question you link to is not using a promise, it is passing a function as the callback, that's quite different I think. – pedalpete Apr 09 '14 at 01:48
  • 2
    It's the same concept, promises are still asynchronous. – Qantas 94 Heavy Apr 09 '14 at 01:49
  • 1
    http://stackoverflow.com/q/22536385/1348195 – Benjamin Gruenbaum Apr 09 '14 at 06:48
  • I also need an answer for this. So basically impossible to write a function with a promise inside which returns the result for `console.log(getValue('myFile.txt'));` function call? If it's true it's sucks, because sometimes even this call is unnecesary boilerplate: `getValue('myFile.txt').then((val) => { console.log(val) });` – Lanti Mar 24 '17 at 12:55
  • 2
    **Actual answer:** https://softwareengineering.stackexchange.com/a/350041/171994 – Andrew Aug 27 '19 at 21:23

2 Answers2

28

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
19

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 8
    You are not wrong, but your solution violates the encapsulation principle. The object or function calling getValue(...) should not know and should not have to know about the function lookupValue(...). This way, if the exact procedure within getValue(...) changes, functions that rely on it do not need to be updated. – Jared Clemence Aug 10 '17 at 21:10