DEV Community

Adrian0506
Adrian0506

Posted on

Javascript Async/await

I have recently learned about JavaScripts Asnyc functions! At first they were really confusing. I have been using them primarily for node.js. The way Async functions work is that say you are reading a file in node js. Let me make a short example.

function readFile () {
let data = readFile('./src/index.txt');
console.log(data)
}
console logs undefined;

The reason this logs undefined is because we are not waiting for the data to come back. We instantly go to the next like to log the data. But since it hasnt come but we do not know what is in data so as a result it logs undefined. Here is a different example of a working solution to this problem.

function readFile() {
readFile('./src/index.txt', function (err, data) {
if (err) {
return err

} else {
console.log(data)

}
});

}

Instead we give it a call back! The call back runs when it finished reading the file and is ready to return a result. We also have a err argument that only runs when a err is found. we could also do this a different way by stopping the code until it comes back with a response, but the problem with this is that it will not run another line of code until it returns a response! It could slow down your application a lot! Here is a example of that.

function async readFile() {
let data = await readFile('./src/index.txt')
console.log(data)

}

This time it will fine the data but the await keyword will stop the code until it receives something in return!

Top comments (1)

Collapse
 
bias profile image
Tobias Nickel • Edited

I am always glad when more folks learn about async await. I am also happy when using markdown, to format the code.

you can wrap your code snippets into tripple backticks (```), above and below your code. then it is easier to read.