-1

I am experiencing unexpected behaviour with arrow functions in JavaScript.

microsoftTeams.initialize();
microsoftTeams.getContext((context) => {
  this.user = context.loginHint!;
  console.log("Arrow function called");
});
console.log("Outside of Arrow Function");

When executing this code inside a React Component's constructor, the code block enclosed in the arrow function is the last one to be called. Even functions called after completions of the construction such as componentDidMount() are called earlier:

FetchFiles.tsx:21 Outside of Arrow Function
FetchFiles.tsx:28 Component did mount
FetchFiles.tsx:19 Arrow function called

I am wondering why the enclosed code block is not executed first. Is this the expected behaviour and if so, what am I missing here?

Beltway
  • 508
  • 4
  • 17
  • 6
    _"Is this the expected behaviour"_ - Yes. _"and if so, what am I missing here?"_ - `.getContext()` is asynchronous – Andreas Nov 03 '20 at 10:04
  • 1
    [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086) – adiga Nov 03 '20 at 10:14

1 Answers1

2

I am wondering why the enclosed code block is not executed first.

When it runs depends entirely on getContext. Apparently it calls the callback asynchronously, which is why the code in the callback runs later than the code following the getContext call.

Callbacks can be called synchronously (such as the one in array sort or map, or string replace) or asynchronously (such as the ones in promise then and catch, or setTimeout). Which it is depends entirely on what the callback is being supplied to.

In this case, it's microsoftTeams.getContext which does call the callback asynchronously, though sadly doesn't explicitly say that (in that small part of the documentation anyway). It it strongly implied by the fact that getContext accepts a callback rather than just returning the context. If it could be retrieved synchronously, you'd expect it to be supplied as a return value, not via a callback. (It'a also implied when that documentation says that callback is "The callback to invoke when the xref:Context object is retrieved.")

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • It is a shame that the term "callback" has become overloaded to mean both the `.map` style synchronous function and the async "something to be called later" :( – Alnitak Nov 03 '20 at 10:07
  • @Alnitak - I don't recall a time in my 30+ years of this stuff when it wasn't used for both of those things. It *would* be really nice to have separate terms, but... – T.J. Crowder Nov 03 '20 at 10:12
  • Thanks, I am somewhat new to the syntax and wasn't aware of asynchron callbacks yet. Is there any way i which I can enforce it to run synchronously here? (Like with the `await` keyword)? – Beltway Nov 04 '20 at 14:59