Promises

This post refers to work on the 26th of July which was day 42 of my #100daysofcode

I have a problem that I guess is probably best solved with promises. So now is the time to get a bit more down and dirty with using promises in Nodejs. Previously I have worked on Nodejs applications that use promises, but I have never been the one that starts the process of using them in the code. I have mostly worked on the innards. I have used promises client side briefly a few years ago to get a basic understanding, but beyond ‘do all this stuff asynchronously and then when it has finished do this thing without blocking in the meantime’ my knowledge becomes sketchy.

I make a side project for the express purpose of learning the bare bones of Nodejs promises without diving into my main use case (using imagemagick to read exif data, which is done in a child process). I decide to use Forbes Lindesay’s Promise library. The documentation for this is probably excellent if you are a hardcore programmer, but I am a front-end developer who came from a design background. And I don’t have any computer science qualifications. Hence it takes me a while to realise the examples are incomplete pseudo-code. I head over to MDN and find a more friendly client side example which I can hack at to make it work on Nodejs.

My basic approach is to make a new Promise that contains all of the code that processes the image and put the resolve call inside of the imagemagick child process callback. I then have that object’s .then() method execute all of the stuff that needs doing to save the processed image data.

Aside from a curious error that arose from me reusing the req object as an argument and mistakenly putting the resolve call outside the callback it went pretty smoothly. The code is probably quite hideously constructed but now that I have it working I can look to improve and extend my use of promises beyond this one small place. I have quite a few nested callback structures to do with the updating of the database which will probably benefit from being promise driven.