DEV Community

Cover image for Promises vs Callbacks in Javascript
Alhiane Lahcen
Alhiane Lahcen

Posted on

Promises vs Callbacks in Javascript

If you are a professional Javascript programmer, you must have previously worked with the Callbacks function and in some cases, you are forced to use an answer function within an answer function within an answer function and so on (especially when dealing with Asynchronous commands such as AJAX operations and dealing with files and databases, etc. .. .) Until you get a relatively complex and hierarchical code as you will see in the following code:

function isUserTooYoung(id, callback) {
     openDatabase(function (db) { 
         getCollection(db, 'users', 
         function (col) { 
             find(col, { 'id': id }, 
             function (result) {
                  result.filter(function (user) { 
                      callback(user.age < 18) 
                    } 
                } 
            } 
        } 
    }

Enter fullscreen mode Exit fullscreen mode

The isUserTooYoung function enables us to confirm that a particular user is an adult (over 18 years old), and for this, the connection is linked to the database, then the user searches to know his age and at last we confirm the age.

Use promises


Using promises, we will see that it gives us a clearer, simpler, and more semantic code. Every function that waits for an answer has a function that then picks up the answer from the function before it and passes it to the second function inside. With this concept, we can rewrite the previous code in a more elegant way as follows:


function isUserTooYoung(id) { 
        return openDatabase(db) 
        .then(getCollection) 
        .then(find.bind(null, {'id': id})) 
        .then(function(user) { 
            return user.age < 18; 
        }); 
    }

Enter fullscreen mode Exit fullscreen mode

This is code in Node.js, but the idea and process are correct for other JavaScript applications.

Certainly, now the code has become clearer to you and easier to understand, as we can say that the openDatabase function promised the getCollection function to access certain data Datas after the successful connection to the database, and if we wanted to use the isUserTooYoung function in our program then it would be this way:


isUserTooYoung(id) 
 .then(function(result) {
   // Here you can deal with the end result
 }


Enter fullscreen mode Exit fullscreen mode

Do not forget that there are other useful functions when using promises in JavaScript, such as the catch function, which is called when an operation or promises is not successful.

If you want to know more about JAVASCRIPT :

Top comments (0)