For my school project, I need to create a sequence diagram. In that sequence diagram I have to represent an API call using simple JavaScript code (fetch()
+ then()
for handling the response).
I’m confused, should I represent this as sync or async communication in a sequence diagram?
In one way, since the web browser is not blocked while waiting for a response I guess it should be async. But in another way, it waits for the response so it can be processed so it’s blocked from executing which means is should be sync?
I tried google-ing this problem but didn’t find any answers.
2
Answers
An HTTP request that returns the response directly is synchronous. For an asynchronous communication, the server would have to send another message, e.g. via a WebSocket.
The
fetch()
API is promise-based and hence asynchronous. Thethen()
method is invoked not synchronously, but asynchronously when the promise is fulfilled, i.e. thefetch()
response finally arrives.Therefore, the right way to model it, is the async call in the right diagram, although, one would expect that the message 4 is send from the end of the activation zone (like for message 3, except that life is going on on the browser side and other activity might start before that incoming message).
If however you use
await fetch()
instead offetch().then()
you would have the choice: while technically, it’s still asynchronous, de facto you’d wait for the promise to be completed before doing anything else, i.e. you behave as if it would be synchronous. So in your modelling, you could focus on your design intent, independently of how you implemented it.