0

I am confused about async and await. to use an await, it should be in an async function, ok, but then how first one will start ?

I have a async function and it has awaits chain inside it. When I refresh it runs and I can see object values but later they disappear. getMyValues is my function and the problem is; when I debug, I can see objects and its values but its disappear when I want to use them later, only I can use strings I get from them, even they disappear sometimes.

So, I have few questions; Q1) Why object become undefined ? I know javascript objects are dynamic, but I see issue even I make a deepclone. How does it happen same session works again and even that session object becomes undefined..

 async function getMyValues() {
 // Initialize a session. 
 var session = await myclass.createSession(5)
 var myValues = session.getValues()

I run like this;

     getMyValues()

Q2) If I put return inside that function and run like that I can see a promise in debug..How to return a value from these kind of functions properly ?

let myvals = getMyValues()

Rasim AVCI
  • 133
  • 2
  • 4
  • 11
  • @PatrickRoberts Not a good dupe target – Blue Jan 20 '18 at 18:06
  • @FrankerZ it's exactly correct. The last line of the question shows the fallacy of assuming you can externally treat the function as synchronous: `let myvals = getMyValues()`. OP wants to know how to "return the response from an asynchronous call" – Patrick Roberts Jan 20 '18 at 18:07
  • what is the link for dublicate question ? – Rasim AVCI Jan 22 '18 at 12:40

1 Answers1

0

Your function will essentially be rewritten to (assuming you return myValues from getMyValues()):

function getMyValues() {
    return new Promise(resolve => {
        // Initialize a session. 
        myclass.createSession(5)
            .then(session => {
                var myValues = session.getValues()
                resolve(myValues);
            });
    });
 }

Now, getMyValues() returns a promise, so you need to handle that asyncronously as well. (Either with .then() or with await on that function:

getMyValues().then(values => {
    console.log('All the boys in the yard like these values: ', values);
});
Blue
  • 22,608
  • 7
  • 62
  • 92