Some Bits: Nelson's log

I don’t understanding looping with Promises

Did some hair-pulling work with Javascript Promises recently. I’m calling a paginated database API (CloudKit JS), so I want to fetch N results at a time until there are no other results to fetch. In simple synchronous programming you’d do this with a while loop. But Promises can’t be reused or iterated in this way, so instead you do something that amounts to tail recursion. The Cloudkit docs have a handy example:

database.performQuery(query, { resultsLimit: 10 }).then(function(response) {
    if (response.hasErrors) {
        // Insert error handling
        throw response.errors[0];
    } else {
        // Insert successfully fetched record code
        if(response.moreComing) {
            return database.performQuery(response);
        }
    }
});

I use code much like this for real and it works. But it’s complicated! database.performQuery is an asynchronous method in CloudKit JS, it is a Promise. This code creates a new query promise, then chains it via .then() to some synchronous code that processes the response. The last thing the processing code does is check if there’s more results to come (the pagination API) and if so it creates a new Promise and returns it. Which causes the Promise execution framework in the browser to go to resolve that new promise next.

It feels very much like tail recursion. I get conflicting answers on whether it genuinely is recursive, in the sense of some Javascript stack or Promises chain growing larger and larger with each request. It’d be simple enough to do basic tail recursion optimization to eliminate that growth, just no idea if implementations do it.

My problem

So I’ve got code working. My problem is the moment I try to do something more complicated, I get lost. As a practical example; what if I want to inject a one second delay between each call to that performQuery() function? I can make a new promise with setTimeout() and chain it in there, but half the time I type the code to do that I get it wrong. I got lucky and it worked once and I don’t really understand why. Then try passing arbitrary parameters conveniently through the call chain; you can, but it’s hard because Promises only take one argument to pass along so you have to stuff your parameters into a new Object. And I haven’t even tried to reason about getting error handling right, although I think if you’re naive and don’t do much of anything then the default reject/catch behavior will probably work.

async/await

There’s a new hotness coming in Javascript with the async and await keywords along with async interation. Here’s another example of it in use. I haven’t ever used this stuff myself and am not sure if it works yet in browsers.

Update: some advice on Twitter to use async/await, that it has decent browser support.

Thinking asynchronously

This is an unsatisfying blog post where I investigated a problem and don’t really have a solution. Honestly, most of the time I do async programming in any language I feel the same way. Python, Javascript, even select()-based C code back in the day. My model of programming computers is so heavily based on imperative execution I always feel all twisted when I program asynchronously.

I need to do a series of exercises fully in an async model and get comfortable. Either that or find a good Javascript wrapper for Promises that provides higher level components like “iterate this set of promises” and the like.

Comments

i feel your pain. not just a frontend thing either, this kind of callback soup slowly grew out of control in Google's C++ (and later Java too), and was one reason Go with channels was such a breath of fresh readability air.

i'm a JS novice too, but i've written a moderate toy app with async/await, and it seemed nice enough, and worked in current Firefox, Chrome, and Safari on Mac at least. the meat of the code is https://github.com/snarfed/baffle/blob/master/routes/newsblur.js