whathetech Javascript,node.js Promises in Javascript/Node.JS

Promises in Javascript/Node.JS

A Promise in Javascript/Node.JS is used for asynchronous programming. This can be used as an alternative to callbacks in Node.JS
Lets just get right into it and understand how to use a promise.

const fs = require('fs');
function promiseFun1() {
    return new Promise(function(resolve, reject) {
        fs.readFile('test.txt','utf8', (err, data) => {
            if (err) {
                return reject(err);
            } else {
                return resolve(data);
            }
        });
    });
}
console.log('Call the promise function.')
promiseFun1().then(response=>{
    console.log(response);
})
.catch(err=> {
    console.log(err);
})
console.log('end of file');

When you run this example (node promises.js), you will see a response like this:

home@home-home-1:~/$ node promises.js
Call the promise function.
end of file
typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

As you can see, ‘end of file’ is printed before the contents of file. This is because the readFile is an asynchronous function and the promise will return the data once readFile returns.

Promise Chaining

Lets us now understand how to chain promises. You might want to do this if you would like to have the data from one function to be passed into another function. Since Promises are async, by chaining the two function we are making them synchronous (well, not really).

Extending our previous example, lets now count the number of words taht we get from the text file.

const fs = require('fs');
function promiseFun1() {
    return new Promise(function(resolve, reject) {
        fs.readFile('test.txt','utf8', (err, data) => {
            if (err) {
                return reject(err);
            } else {
                return resolve(data);
            }
        });
    });
}
function wordCount(text) {
    return new Promise(function(resolve, reject) {
        words = text
                .replace(/[.,?!;()"'-]/g, " ")
                .replace(/\s+/g, " ")
                .toLowerCase()
                .split(" ");
      return resolve(words.length);
    });
}
console.log('Call the promise function.')
promiseFun1().then(response=>{
    return response;
}).then(sentences=>{
    return wordCount(sentences);
}).then(numWords=>{
    console.log('index = ', numWords);
})
.catch(err=> {
    console.log(err);
})
console.log('end of file');

Response:

home@home-home-1:~/$ node promises.js 
Call the promise function.
end of file
index =  83

What the first Promise did was to get the text from the file and pass it on to the next one in the chain. The second one takes the response from the first promise as an input and counts the number of words in the text and returns the total number of words which is resolved and printed in the chain.

I hope this has given you some understanding of how promises work and what promises are. You can now jump to http://whatthetech.co/promises-in-javascript-and-node-js-part-2-using-promise-all-and-javascript-map/ to learn about Promise.map, Promise.all, and many more.

Tags: , ,