NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
What is await and async in NodeJs?
"await" keyword within the function, we need to add "async" keyword in front of the function. The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code.
File Name :
result = await expression
expression :- A Promise or any value to wait for.
result :- Returns the fulfilled value of the promise, or the value itself if it's not a Promise.
Example
that the bcrypt.hash() function may take a while to generate the hash, and so we use the "await" keyword in front of it.
File Name :
app.post("/createUser", async (req,res) => {
const user = req.body.name;
var password = req.body.password;
const hashedPassword = await bcrypt.hash(password,10);
});
The await expression causes async function execution to pause until a Promise is settled and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value.
simply await the function that returns the Promise.
The await keyword is used inside the async function to wait for the asynchronous operation.
The use of await pauses the async function until the promise returns a result (resolve or reject) value.
Examples
Awaiting a promise to be fulfilled :-
If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.
File Name :
function resolve_After_two_Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function test() {
const a = await resolve_After_two_Seconds(10);
console.log(a); // 10
}
test();
File Name :
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
// wait until the promise resolves
let result = await promise;
console.log(result);
console.log('hello');
}
// calling the async function
asyncFunc();
async function :-
async keyword with a function to represent that the function is an asynchronous function. The async function returns a promise.
File Name :
async function name(parameter1, parameter2, ...paramaterN) {
// statements
}
name - name of the function
parameters - parameters that are passed to the function
Thenable objects :-
Thenable objects will be fulfilled just the same result.
File Name :
async function test() {
const thenable = {
then(resolve, _reject) {
resolve('resolved!')
}
};
console.log(await thenable); // resolved!
}
test();
Example: After async/await
File Name :
async function show(req, res){
let response = await request.get('http://ittutorial.in');
if (response.err)
{
console.log('error');
}
else
{
console.log('fetched response');
}
}
The above code asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.
Promise
In JavaScript, a promise is a good way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not.
A promise may have one of three states.
A promise starts in a pending state. That means the process is not complete. If the operation is successful, the process ends in a fulfilled state. And, if an error occurs, the process ends in a rejected state.
File Name :
For example, when you request data from the server by using a promise, it will be in a pending state. When the data arrives successfully, it will be in a fulfilled state. If an error occurs, then it will be in a rejected state.
Create a Promise
To create a promise object, we use the Promise() constructor.
File Name :
let promise = new Promise(function(resolve, reject){
//do something
});
The Promise() constructor takes a function as an argument. The function also accepts two functions resolve() and reject().
If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called.
File Name :
Example:-
const count = 5;
let result = new Promise(function (resolve, reject) {
if (count) {
resolve("success");
} else {
reject("error occurs");
}
});
console.log(result );
Output :-
File Name :
Promise Chaining
Promises are useful when you have to handle more than one asynchronous task, one after another.
You can perform an operation after a promise is resolved using methods then(), catch() and finally().
then() method
File Name :
The then() method is used with the callback when the promise is successfully fulfilled or resolved.
The syntax of then() method is:
promiseObject.then(onFulfilled, onRejected);
Example 2: Chaining the Promise with then()
File Name :
// returns a promise value
let res_obj = new Promise(function (resolve, reject) {
resolve("Promise resolved");
});
// executes when promise is resolved successfully
res_obj
.then(function successValue(result) {
console.log(result);
})
.then(function successValue1() {
console.log("You can call multiple functions this way.");
});
Output :-
You can call multiple functions this way.
JavaScript catch() method
The catch() method is used with the callback when the promise is rejected or if an error occurs.
File Name :
// returns a promise
let countValue = new Promise(function (resolve, reject) {
reject('Promise rejected');
});
// executes when promise is resolved successfully
countValue.then(
function successValue(result) {
console.log(result);
},
)
// executes if there is an error
.catch(
function errorValue(result) {
console.log(result);
}
);
File Name :
JavaScript Promise Methods
File Name :