This post appears to be about JavaScript’s Promises vs await debate, which is explained in way more detail in this post on hackernoon. Read the post. It’s great.
To summarise it, the original JavaScript Promise API is superseded by await.
This does not mean that everything that allowed for Promises or depended on them has gone away. In particular, you can still see unit tests a bit like this in mocha.
it('displays the home page', (done) => { // a test library for calling the async // method on our server makeRequest(server, '/homepage') .andExpect(200) // asserts the status code .then((response) => { assertHomePageIsVisible(response); done(); }); });
It’s not wrong to still write code this way, though one should always use the best technique that’s available, so long as it doesn’t imply a huge disruption to the current project (or sometimes especially if it creates that disruption).
Where life gets complicated is with an example like this:
it('displays the home page', async () => { let response; // a test library for calling the async // method on our server await makeRequest(server, '/homepage') .andExpect(200) // asserts the status code .then((resp) => { // capture the response for asserting when this // promise completes response = resp; }); assertHomePageIsVisible(response); });
So we have a promise with its then being awaited and setting a temporary variable to make something known to the subsequent scope. What the actual WTF?
A Mixed Metaphor Never Prospers
It’s really important to review the code you wrote to ask whether each function./module is being consistent within itself. If it’s using two method for the same thing, do they overlap? If I rewrote the above as I would prefer, it would look like this:
it('displays the home page', async () => { // a test library for calling the async // method on our server const response = await makeRequest(server, '/homepage') .andExpect(200); // asserts the status code assertHomePageIsVisible(response); });
This still uses something promise-like, because there’s no alternative in the test library, but it predominantly uses the desired pattern. It’s also enormously SIMPLER!
It would have been a reasonable thing with the promise-like library to standardise on the Promise approach from the start, but once you get used to not having to have nested functions for everything it’s hard to want them back.
Every change in metaphor adds complexity to the job of the future reader and should be avoided.