Promiseland and Async/Await Kingdom
Last night I finally got a chance to publish the remaining setup scripts for my E-Commerce Chatbot. A few days ago, I added the script to load up products and variants into Azure Search and now also the catalog and historical transactions for Azure Recommendations. I basically had to script what I originally did as a one-off with
curl
.
Training the recommender model takes time and when you create a new recommendation build, it won’t be ready right away. I wanted my script to wait and keep polling the API until the training has finished. The whole script is basically a serious of asynchronous HTTP requests so I wired it all up as a chain of promises:
1 | sdk.model.list() |
You can see the full listing here.
Promiseland
Here’s how I implemented the wait-and-see:
1 | // ... |
It’s basically a recursive promise. The function in the main then()
will return a promise that will always resolve unless there’s an error, but the key is in what it will resolve with and how it runs. The function that the returned promise is wrapped around schedules itself via setTimeout()
and exits the stack frame. Then, when the response is received, it will either resolve and signal that the training has complete, or it will resolve with another promise that will recursively repeat this process again. That another promise will basically insert itself into the main then
chain and it will keep waiting until it resolves. Vicious circle.
It worked nicely and I even factored out the repeater
so that my code looked like this:
1 | // ... |
Async/Await Kingdom
I really thought that I was very cleaver but then I decided to rewrite with
async
/await
and run with the latest node that now natively supports it
Here’s what this code became:
1 | let trained = false; |
Here. Compare both versions: Original vs. Async/Await
It’s not even funny! The code is so boring now, boring and simple. Just like it should be. No need to be clever and I bet I will know exactly what it’s doing and why when I look at it a year later.
I have officially converted.
Cheers!
Promiseland and Async/Await Kingdom