DEV Community

Tadea Simunovic
Tadea Simunovic

Posted on

2 1

Asynchronous JavaScript

I'm sure you heard of 'AJAX', and if you are a beginner, wondering what does it means and how it is used in JavaScript?

AJAX = Asynchronous JavaScript and XML. XML(Extensible Markup Language) is a format, lightweight that is used to send data from browser to server and server to browser. The most common way of sending data nowadays is a JSON (JavaScript Object Notation).

Yes, JavaScript is a synchronous language. Which means only one operation can be carried out at a time. That’s where AJAX comes into play. Using asynchronous JavaScript (such as callbacks, promises, and async/await), you can perform long network requests without blocking the main thread.

Synchronous code is executed one after the other. This means each statement has to wait for the previous one to finish executing.

const second = () => {
    console.log('Second');
}
const first = () => {
    console.log('Hey there');
    second();
    console.log('The end');
}

first();
// Hey there
// Second
// The End
Enter fullscreen mode Exit fullscreen mode

Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting. I will add setTimeout function, which is a timer in JavaScript, that allows us to write code that will be executed later.

const second = () => {
    setTimeout(() => {
      console.log('Hey There Async')
    }, 2000)
}
const first = () => {
    console.log('Hey there');
    second();
    console.log('The End');
}

first();
// Hey there
// The End
// Hey There Async (this will appear after 2 seconds)
Enter fullscreen mode Exit fullscreen mode

setTimeout does not pause the execution of the code. It only schedules something to happen in the future, and then immediately continues to the next line.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay