-2
$(document).ready(()=> {
    window.chat = Chat();
});
Chat = async function() {
    this.hello = "world";
    // more code
}

when I type in chat in the console, I got

Promise {<fulfilled>: undefined}

When I type chat.hello, I got undefined error

How can I get or access chat.hello from the debug console ?

I also tried

$(document).ready(async ()=> {
    window.chat = await Chat(); // this is NEVER called 
});
yarek
  • 11,278
  • 30
  • 120
  • 219

1 Answers1

1

There are a few issues with that code:

  1. this within the call to Chat will either be undefined (in strict mode) or the global object (in loose mode), so this.hello = "world" will either fail (in strict mode) or add a property to the global object.

  2. There's no Chat.hello property. Chat is a function object. You could put a hello property on it (Chat.hello = x), but that would be an unusual thing to do.

  3. It's correct that you see a promise when you look at chat. async functions return promises, and you're creating the chat property by assigning it the result of calling an async function. The answers to this question for how to use the value from a promise.

You could make Chat a constructor function and call it via new. async functions can't be constructor functions, though, so you'd probably want to make the async part a method on the returned object.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875