Js Notes
Js Notes
js:
timeout,
interval,
immediate.
a) timeout timers:- Timeout timers are used to delay work for a specific amount
of time. When that time expires, the callback function is executed and the timer
goes away. Use timeouts for work that only needs to be performed once.
The Node.js setTimeout function is built in the Node.js function that runs the
specified program after a certain period of time passes. This time is always defined
in milliseconds. setTimeout() accepts a callback function as the first argument
and the delay time as the second. If the delay argument is omitted, it defaults
to 0.
1. Without Arguments
function callbackFunction() {
// Code here
setTimeout(callbackFunction, delayTimeInMS)
function greet(fname,lname) {
console.log('Hello'+fname+lname);}
console.log("Print first")
clearTimeout:-The setTimeout() function returns a timer object ID. You can pass
this ID to clearTimeout(timeoutId) at any time before the delayMilliSeconds
expires to cancel the timeout function. For example:
clearTimeout(myTimeout);
Example:-simple_timer.js:
function simpleTimeout(consoleTimer){
Node.js EventEmitter:- Node.js uses events module to create and handle custom
events. The EventEmitter class can be used to create and handle custom events
module.
The syntax to Import the events module are given below:
Syntax:
Const EventEmitter = require('events');
All EventEmitters emit the event newListener when new listeners are added
and removeListener when existing listeners are removed.
Listening events:- Before emits any event, it must register functions(callbacks) to
listen to the events.
Syntax:
eventEmitter.addListener(event, listener)
or
eventEmitter.on(event, listener)
eventEmitter.on(event,listener) and eventEmitter.addListener(event,listener) a
re pretty much similar. It adds the listener at the end of the listener’s array for the
specified event. Multiple calls to the same event and listener will add the listener
multiple times and correspondingly fire multiple times. Both functions return
emitter, so calls can be chained.
Emitting events: Every event is named event in nodejs. We can trigger an event
by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary set of
arguments to the listener functions.
Syntax:
eventEmitter.emit(event, [arg1], [arg2], [...])
Example:-
// Importing events
Const EventEmitter = require('events');
// Initializing eventemitter instances
Var e = new EventEmitter();
// Registering to myEvent
e.on('myEvent', (msg) => { console.log(msg);});
// Triggering myEvent
e.emit('myEvent', "First event");
Output:-
First event
Removing Listener: The eventEmitter.removeListener() takes two argument
event and listener, and removes that listener from the listeners array that is
subscribed to that event. While eventEmitter.removeAllListeners() removes all
the listener from the array which are subscribed to the mentioned event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
What is a promise?
resolve("Correct");
} else {
reject("Wrong!!");
})
};
isLessThan10(14);
The pending state is the initial state that occurs when a promise is called. While a
promise is pending, the calling function continues to run until the promise is
completed, returning whatever data was requested to the calling function.
When a promise is completed, it ends in either the resolved state or the rejected
state. The resolved state indicates that the promise was successful and that the
desired data is passed to the .then() method.
The rejected state indicates that a promise was denied, and the error is passed to
the .catch() method.
Creating a custom promise
function getSumNum(a, b) {
const sum = a + b;
resolve("Let's go!!")
} else {
})
return customPromise
Chaining promises
Promises can be used to execute a series of asynchronous tasks in sequential
order. Chaining multiple then() Promise outcome helps avoid the need to code
complicated nested functions (which can result in callback hell).
To demonstrate chaining promises, let’s utilize the previous code with a few
modifications:
let value;
function getSumNum(a, b) {
const customPromise = new Promise((resolve, reject) => {
const sum = a + b;
return customPromise
}
getSumNum(1, 3)
.then(data => {
console.log("initial data: " + data)
value = data + 1 // modifying the returned data
return value
})
.then(newData => {
console.log("modified data: " + newData)
})
.catch(err => {
console.log(err)
})
.then(response => { // Call this when status and headers are ready
// Now check the headers to ensure that the server sent us JSON.
return response.json();
})
if (profile) {
displayUserProfile(profile);
else { // If we got a 404 error above and returned null we end up here
displayLoggedOutProfilePage();
})
.catch(e => {
if (e instanceof NetworkError) {
else {
console.error(e);
});
await Expressions
The await keyword takes a Promise and turns it back into a return value or a
thrown exception. Given a Promise object p, the expression await p waits until p
settles. If p fulfills, then the value of await p is the fulfillment value of p. On the
other hand, if p is rejected, then the await p expression throws the rejection value
of p.
async Functions
Because any code that uses await is asynchronous, there is one critical rule: you
can only use the await keyword within functions that have been declared with the
async keyword.
Example:-
return profile.highScore;
Declaring a function async means that the return value of the function will be a
return value of the function will resolve to that apparent return value. And if an
async function appears to throw an exception, then the Promise object that it
returns will be rejected with that exception.
displayHighScore(await getHighScore());
(OR)
getHighScore().then(displayHighScore).catch(console.error);
return body;
And now suppose that we want to fetch two JSON values with this function:
Step 1: Save the file as index1.js and paste the below code inside the file.
function add(a, b) {
return parseInt(a)+parseInt(b)
node index1.js 2 3
Node is Asynchronous by Default
Example:-
const fs = require('fs')
readdir('process.cwd()')
.then(files => {
console.log(files)
})
.catch(err => {
console.log(err)
})
Streams:-
Implementing a Readable Stream: We will read the data from inStream and
echoing it to the standard output using process.stdout.
Example:-
// a Readable Stream
// Accessing streams
read() { }
});
inStream.push('GeeksForGeeks : ');
inStream.push(null);
inStream.pipe(process.stdout);
Output:
Pipe:-
Parameters: This method accept two parameters as mentioned above and described
below:
Example:-
// readable.pipe() method
// Accessing fs module
var fs = require("fs");
readable.pipe(writable);
console.log("Program Ended");