Promises Save The Day

Unfortunately Parse is closing down in 2017, but we have found a great and actually local (to us) service: AppStax.

In the past few days we’ve experienced a (possible belated) revelation about the promise-paradigm of programming, which may be familiar to you if you’re into jQuery.

Until now, we hadn’t really been able to realize what promises could do for us in our own code even though we’ve used them indirectly with Parse.com’s framework. Here’s a great blog post from Parse.com about Promises.

A promise in programming is basically a way of saying, look, I’ll do what you told me to do, and I’ll let you know in a while if I was able to or not.

The cool thing about promises is that you can chain them together. This is particularly useful if you don’t want asynchronous tasks (such as networking or IO) to be fired in parallel, but rather in a strict sequential order.

In a previous post, I told you about the ‘series’ method from the Node.js library called async.js, but this time around I needed more flexibility.

I was going to make some sequential tests on an object. The tests themselves involved networking. Moreover, I had to make sure that if an object satisfied some test, it would bypass the remaining tests.

It turns out, this is elegantly solvable with the promise-paradigm. This example is written with Parse.com’s Promise, but I suspect it will not look much different in Backbone.js.

Imagine that I want three rules that check if a vehicle is either a car, a bus or a train, respectively:

[CodePen height=450 show=js href=duCtL user=testower ]

With network-intensive tasks, it would be silly of me to check if a vehicle is a train, if I already know that it is a bus.

Here’s what the rule ‘isACar’ would look like. You can imagine the others:

[CodePen height=375 show=js href=fjLFB user=testower ]

Basically, my rule is a function that accepts an object and a task. The object is what I want to apply my rule to, and the task is another function that I will call in the event that the rule was satisfied.

As you can see, I also rejected the promise when the rule was satisfied. This ensures that the remaining tests in my chain are bypassed. If the rule is not satisfied, I «resolve» the promise, and the next rule in the chain will be applied.

Neat?

Unfortunately Parse is closing down in 2017, but we have found a great and actually local (to us) service: AppStax.

Legg inn en kommentar