3 ms·
There is another use case for async in client-side JavaScript that often gets overlooked: modeling the flow of UI. So, let's say you need to show a "dialog" wh
by branko_d 4y ago
There is another use case for async in client-side JavaScript that often gets overlooked: modeling the flow of UI.
So, let's say you need to show a "dialog" which, upon exit, should execute a piece of code (e.g. to show another piece of UI). Maybe that dialog can be invoked from multiple places, and the code to execute (after the dialog) changes accordingly.
You could do that via callbacks, but that is not very composable, and is generally messy.
Better solution: a Promise which gets resolved when the user exits the dialog! Composing multiple pieces of UI then becomes equivalent to composing multiple (async) function calls, you can pass output from one as the input to another, use exceptions to "circuit break" the UI flow, etc.
- 8n4vidtmkvmk 4y agoI'm not convinced of the dialog use-case. Seems rather sketchy to await a user to click OK. What happens when you add another button or two to the dialog?
- branko_d 4y agoYou return a different result (i.e. the Promise resolves to a different result). The calling code can then decide what to do with it.
- El_RIDO 4y agoIn this model, you wouldn't await the user clicking OK, but exiting the modal. The promise only resolves "user took a decision", not the actual choice they took. The result then contains if the user clicked OK, Cancel, [X] to close the modal or any other state transition that you may have added to that dialog. The recipient (not necessarily the caller that initiated the dialog, in case you chain the responses) can then act accordingly and presumably triggers a different action on OK then the other state transitions.