Skip to content

How to write Asynchronous code in JavaScript

Last updated on February 27, 2021

In this blog post, you will be going to learn what are all the different ways we have while writing Asynchronous code in JavaScript.

This would be needed if you write some POC/Data mimic part when comes to Front-end apps, so that the particular feature can be tested which involves data retrieval part.

Writing Asynchronous code in JavaScript

This is the API we remember in the first place while writing asynchronous code, let’s say we want to mimic some data to return after n number of seconds/mins.

setTimeout(() => {
  // Code should execute after 1 second
}, 1000);

After ES6 release, we have a native Promise API available in JavaScript which makes writing asynchronous code easier.

new Promise((resolve, reject) => {
  resolve(<DATA>);
});

This is similar to Promise but data would be streaming.

new Observable(subscriber => {
 setTimeout(() => {
   subscriber.next(<VALUE>);
   subscriber.complete();
 }, 2000);
});

This is a bit advanced but writing would be easy. This can be identified with * the symbol associated next to functionkeyword.

function* GetMessage() {
  yield 'Cool Message';
  yield 'Test Message';
}

const message = GetMessage();
console.log(message.next().value); => 'Cool Message';
console.log(message.next().value); => 'Test Message';

The above ways are helpful in simulating asynchronous operation in JavaScript. You could share your ideas if you come across different than the above one.

Published inAngularFrameworksJavaScriptReact