The async and await keywords in javascript

Here I’m going to explain what does means by async and await in javascript and node js.

Async

The async keyword is used to making a function asynchronous that means Asynchronous code allows the program to be executed immediately where the synchronous code will block further execution of the remaining code until it finishes the current one

Await

The await keyword will ask the execution to wait until the defined task gets executed.
If you use the async keyword before a function definition, you can then use await within the function. When you await a promise, the function is paused in a non-blocking way until the promise settles. If the promise fulfills, you get the value back.
await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves.

Examples: 1

//In normal case if you are using without async and await
const func = () => {
var res= “Hello second”;
console.log(res);
}
console.log(“first”);
func();
console.log(“last”);
OUTPUT:
first
Hello second
last

Example: 2

//If you are using same example here with async and await keyword
const func = async() => {
var res= await “Hello second”;
console.log(res);
}
console.log(“first”);
func();
console.log(“last”);
OUTPUT:
first
last
Hello second

Example: 3

above i have to explained normal cases and here i’m going to explain how to use whole programming code withing async function and this is the best practice.

const func = async() => {
console.log(“first”);
var res= await “Hello second”;
console.log(res);
  console.log(“last”);
}
func();
OUTPUT:
first
Hello second
last

News Reporter
IT Software and web development, Core PHP, JavaScript, JQuery, HTML, CSS, CakePHP, Angularjs, Codeigniter etc.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code