peterforgacs
7/28/2016 - 4:40 PM

Callbacks vs Promises

Callbacks vs Promises

'use strict';

var FS = require('fs');

// Callback version
FS.readFile('file.txt', 'utf8', function (err, data) {
    if (err) throw err;
    console.log('File has been read:', data);
    console.log
});

console.log('After readFile.');

// Promise wrapper version
function readfile(filename) {
    return new Promise(function (resolve, reject) {
        FS.readFile('file.txt', function (err, data) {
            if (err) {
                reject(err);
            }

            resolve(String(data));
        });
    });
}

// Calling the promise wrapper version
readfile('file.txt')
    .then(function (data) {
        console.log(`File has been read: ${data}`);
        return (data);
    })
    .then(function (param) {
        console.log(`After passing to the next ${param}`);
    })
    .catch(function (error) {
        console.log('Error has happened:', error);
    });