If you’ve read my last post, then you know that I am having all kinds of geeky fun with Moltin and its APIs. Today I will show you how you can quickly promisify them all.
Moltin APIs
Moltin APIs are all asynchronous HTTP calls with very lightweight wrappers for JavaScript, Python, and many other languages. I am using it with node.js and the main pattern is fairly straightforward (look for js examples).
I am writing a batch import to create a playground product catalog so I find myself doing a lot of this:
inventory.then((data) =>Promise.all(data.products.map(p => { return moltin.Product.Create(...); }))).then((products) =>Promise.all(products.map(p => { return moltin.Modifier.Create(...); }))).then((modifiers) => { // ... a lot cleaner and more readable, isn't it? });
Promisification
There’s moltin-util on NPM that uses Promises but it seems to introduce a new API and I would like to retain the original. Here’s what I quickly put together and I now wonder if it’s worth posting to NPM. Is it? Let me know!
module.exports = function (moltin) { returnpromisify(moltin); };
My code is now a whole lot cleaner and smaller too. I will soon post it on Github so stay tuned! Here is, for example, how I would go about deleting a whole bunch of products: