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.
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)