DEV Community

Petar Prokopenko
Petar Prokopenko

Posted on

Async done simple

Javascript is single core programing language. That can be good thing if you want to interact with HTML DOM(document object model), or you are doing small project. In other cases if you are working on mean stack(MongoDB, express, angularjs, node.js) or other system you are probably using async functionality.

How does it works:

Best way to understand is from example. Let's say that you are in a coffee shop and you want one cup of black coffee. You order you coffee from Maria, she call's you when is ready, and you get your coffee. Your desire for coffee is new async call, When Maria say wait for coffee that is promise. Maria calls you that your order is ready is resolve. if there are any problems Maria will tell you and that is reject.

If you are using "vanilla" javascript async without any packages it looks something like this:

function myAsyncFunction(url) {
    return new Promise((resolve, reject) => {
        Your code goes here
    });
};
Enter fullscreen mode Exit fullscreen mode

It looks simple, we sould all do it like that!

NO!

Here is why:

For me personally, putting all code inside another function is bad for reading the code, it can get messy, clutted and hard to read. If I can, I will never put my code inside of another function(exept for callback functions).

Its good for small functions, that dont have to many line, and they are simple.

Then I thought to myself how I can improve it, make it object oriented and simple. After week and a half I came with this solution:

exports.simpleAsync = function () {
    this.resolve;
    this.reject;
    this.promise = new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
    });
};
Enter fullscreen mode Exit fullscreen mode

It is simple, clean, lightweight and easy to use. It can be used similarly like good old q pacakge for async.

How should you use it:

var Async = require('simplify-async').simpleAsync;

    function test() {
        var promise = new Async();

        setTimeout(() => {
        promise.resolve("Have nice day");
        }, 5000);

        return promise.promise;
    }

test().then((response) => {
    console.log(response)   
}).catch((err) => {
    console.log(err);
});
Enter fullscreen mode Exit fullscreen mode

Let me expalin what is goind on:

Test is async function. First thing is that you have to make new instance of Async package that you imported with require function. Next is that you have to return promise, because if you don't js will return error that goes something like this: cannot read property .then of undefined. After you get your data, all you need to do is call promise.resolve funtion and async call will be finished.

I hope this small, and super simple async package will help you do more!

If you want to checkout my package it's on github:

https://github.com/PetarProkopenko/simple-async

Link to npm package is:

https://www.npmjs.com/package/simplify-async

Note: I'm not doing this just for promotion, I'm doing it becuse I love programming and I want to contribute to community.
This is my first article and package, if you have any idea let me know, or if I did something wrong...
Thank you for your time and for reading, I hope you have nice day.

Top comments (3)

Collapse
 
lucretius profile image
Robert Lippens

An interesting take on the wonderful async world of JavaScript. I have a few questions:

1) I know this was your preference, but why the desire to make JavaScript appear more object-oriented? It's always struck me as a more functional language, with very language-important features like closures for example.

2) why use promises alone when ES6 introduced generators and the latest versions introduced async/await - which can be transpired down with babel on the frontend or used with the right version of Node on the backend? They both make working with async code very nice.

Collapse
 
petarprok profile image
Petar Prokopenko

Hello Robert and thank you for reading my article.

Answers to your questions:

1) The beauty of javascript is that every function you create can be assigned to object and passed as reference for callback functions when you are using express routes. Example: you have routes in one file and ctrl in other. By exporting function in ctrl and requiring ctrl file in routes you can pass ctrl fun in route.
app.get('/', ctrl.testFunction);

2) Yes you can use async/awit. Not everyone uses babel compiler, most of the projects now days are using reactJS, angular, etc. Async/await for node is supported in 7.6 version and if you have project that uses older version you can't do that.

I made this package simple and small, so you can use it in any framework just with couple of lines you can do you async things. Async/awit is good, but most
of devs are still promises. If I read correctly async/awit is new thing from ES8?

Happy coding.

Collapse
 
lucretius profile image
Robert Lippens

Ah so with objects you were referring more to what you’d do with module exports? I can’t disagree with that as that’s exactly what I do. Within those modules though , you could make other functions external to your exports which you could pass as function arguments or use internally (mimicking the idea of private functions)

Async await are available in node 7.6.0+ but generators have been around for a while longer. I think Node 8.5 just got released. Most of my JS work these days is on the backend so I haven’t needed Babel in a while but for a plain JS solution that runs on all browsers I’d say native promises or a wrapper like you’ve made are great choices!