Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value after a promise [duplicate]

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.

like image 831
pedalpete Avatar asked Apr 09 '14 01:04

pedalpete


People also ask

How do you get the return value of a promise?

Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.

How do you assign a value of a promise to a variable?

To assign value from successful promise resolve to external variable with JavaScript, we use async and await. const myFunction = async () => { vm. feed = await getFeed(); // ... }; to get the resolve value of the promise returned by getFeed with await .

How do I return after promise?

there is a way to return a value from a promise? the return value of a then() call is again a promise, which wraps the value your returned. test is undefined because justTesting returns nothing in your example (you have no return). Add a return and test will be defined as a promise.

How do I return a promise in TypeScript?

Use the Awaited utility type to get the return type of a promise in TypeScript, e.g. type A = Awaited<Promise<string>> . The Awaited utility type is used to recursively unwrap Promises and get their return type. Copied!


Video Answer


2 Answers

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)

like image 52
SomeKittens Avatar answered Oct 14 '22 03:10

SomeKittens


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.

like image 38
thefourtheye Avatar answered Oct 14 '22 03:10

thefourtheye