InterviewSolution
| 1. |
What are Promises? |
|
Answer» Promises in simple words could be explained as advanced call back functions. Whenever multiple callback functions needed to be nested TOGETHER Promises could be used. Promises avoid the callback hell PRODUCED by nesting together many callback functions. A promise could take up three states defined by the 'then clause'. Fulfilled state, rejected state, and pending state which is the initial state of promise. Let’s take the example of reading a file and parsing it as JSON 1. Synchronous method of writing the code function readJSONSync(filename) { return JSON.parse(fs.readFileSync(filename, 'utf8')); }2. Asynchronous method of writing the code using callback. Introducing callbacks make all I/O functions asynchronous. function readJSON(filename, callback){ fs.readFile(filename, 'utf8', function (err, res){ if (err) return callback(err); callback(null, JSON.parse(res)); }); }Here a callback PARAMETER confuses a bit so we replace it with promise 3. IMPLEMENTATION Using Promise function readFile(filename, enc){ return new Promise(function (fulfill, reject){ fs.readFile(filename, enc, function (err, res){ if (err) reject(err); else fulfill(res); }); }); }Here we use “new Promise” to construct the promise and pass a function to the constructor with two arguments. The first one fulfills the promise and the second one rejects the promise. To start working with promises we need to install the “promise” module first using the command “npm install promise” |
|