0

I am trying to find a simple example of how to return a value from async/await where the value is easily accessed outside the async function.

Would the following two examples be considered the optimum way to return a value from an async/await function?

In other words, if the value returned from an async/await needs to be saved and used in other parts of the code, what would be the best way to save the value?

this is the easiest example i could find:

async function f() {
    return 1;
}
var returnedValue = null;   // variable to hold promise result 
f().then( (result) => returnedValue = result );   
console.log(returnedValue); // 1

or perhaps would it be better to use an object?

async function f(varInput) {
    varInput.value =  1;
}
myObject = {} ;  myObject.value=null;  
f(myObject);
console.log(myObject.value);  // 1

thank you.

edwardsmarkf
  • 1,151
  • 1
  • 10
  • 26
  • 7
    It's unclear what you're asking us. Is there something wrong with the code above which is giving you a problem? Or you want us to explain it to you? – ADyson Sep 28 '18 at 15:43
  • 1
    `.then()` is always called asynchronously (on a future tick of the event loop) so `console.log(returnedValue);` runs BEFORE `returnedValue = result` runs. You use the result of a `.then()` handler INSIDE the `.then()` handler, not outside it. – jfriend00 Sep 28 '18 at 16:08
  • i am looking for the optimum way to handle this situation. – edwardsmarkf Sep 28 '18 at 16:36
  • The optimal way is to NOT do either of the things you're trying to do. That's NOT how you program with asynchronous code or with promises. You must USE the value inside the `.then()` handler or in a function you call from the `.then()` handler and pass the data to. That's how you have to program with asynchronous operations. – jfriend00 Sep 28 '18 at 16:38
  • thank you very much jfriend00. what if the result of the async/await function needs to be saved? – edwardsmarkf Sep 28 '18 at 16:41

1 Answers1

0

My answer addresses two subjects here: 1) Async function returns a promise that resolves to a value. So, for instance your first function can be used as per your example. It can also be used like this:

async function() {
const x = await f();
}

2) Immutability - the second solution will work but it makes your funciton "impure". It is not bad in itself, but beware of side effects this might cause (for instance, if you change an app-wide singleton value without other components being notified about it, some part of your app might go out of sync with the data). Hope this answers your question.

yccteam
  • 1,819
  • 3
  • 19
  • 42
  • could you please expand your answer a bit, perhaps to include how your async/await example might double an input, for example? – edwardsmarkf Sep 28 '18 at 16:38