Skip to main content

Async / Await vs Promises

## Node.JS


In node.js, asynchronous operation able to done by two ways. They are async/await codeblock or promises. What different between them?

### Promises

In promises, some of them call it `callback hell` because of the syntax keep repeating callback like and until the end of the async operation. Here come with an example.

```js
samplePromise: () =>
{
 var promise = new Promise((resolve, reject) =>
 {
  try
  {
   // async codeblock
   resolve(result);
  }
  catch (e)
  {
   reject(e);
  }
 });

 promise.then(
  (result) => {
   // result is returning and async operation run complete.
  },
  (rejected) => {
   // rejected something wrong when running async operation
  }
 ).catch(
  (error) => {
   // unhandled error occurs when running async opeartion
  }
 );
}
```

With this example, you able see that promise code block is quite long when running an async operation, try to think what if more complex async operation required to run, like you need to get data from backend and then get data from other 3rd party and then checking and then only apply. With all of these action you will see that code is quite messy. 


### Async/Await

But what these in async/await syntax? async/await has break this `callback hell` by using reserved keyword async at method code block and await inside function body to declare method is async action ( will be automatically return Promise ) and await declare action need to wait for async opeartion complete. 

```js
samplePromise: async () =>
{
 var promise = new Promise((resolve, reject) =>
 {
  try
  {
   // async codeblock
   resolve(result);
  }
  catch (e)
  {
   reject(e);
  }
 });

 try
 {
  // Must remeber he is not function. so just called like this.
  const result = await promise; 
  const result2 = await promise;
  const result3 = await promise;
  const result4 = await promise;
 }
 catch (ex)
 {
  // error handling code block
 }
}
```

As you have seen, async/await codeblock is shorter and more clear for but i still suggest if you new into javascript please take time to know about promises & async/await still important to you for future develop & develop with teams. As of me, i allowed my mates use Promise / async&await since everyone have own choice due to backend part used microservices so able to do this if not some async/await and some promise would be messy.

## Another important part you need to know.

### Async/Await & Promise Compability

All of the functions with async keyword would automatically return Promise so you can solve it via async/await or promises. So more easierly to work with your mates without conflict, clashing or anything on syntax.

```js
async function sample()
{
 return "ABC";
}

function sample()
{
 return new Promise((resolve, reject) => resolve("ABC"));
}

sample().then(result => console.log(result));
await sample();

[OUTPUT]
ABC
ABC
```

### Stream based async action 

Stream based async action would be some problem if you return without Promise in async function. You will see your code has not been waited. This is my personal experience & problem meet when building async/await codeblock.

```js
async function upload()
{
 /* Sample stream */
 const stream = file.createWriteStream({
  validation: 'crc32c',
  metadata: {
   contentType: 'image/png'
  }
 });

 stream.on('error', error =>
 {
  throw {
   message: `Error occurs when uploading image to storage`,
   stack: error
  };
 });

 stream.on('finish', () =>
 {
  return {
   message: `Image uploaded succesfully.`,
   result: fileId
  };
 });

 stream.end(base64);
}

await upload();

[OUTPUT]
undefined
```

Normally you see the code doesn't have problem but when run the code will go through and never wait and unable get return result. Why? As i above said return value will automatically apply Promise but for stream it apply at the return value part so it running inside stream event listener instead of the function block so will keep going until end of the code and return undefined. For such situation you need to apply the Promise yourself instead of auto apply by async keyword.

```js
async function upload()
{
 const stream = file.createWriteStream({
  validation: 'crc32c',
  metadata: {
   contentType: 'image/png'
  }
 });

 return new Promise((resolve, reject) =>
 {
  stream.on('error', error =>
  {
   reject({
    message: `Error occurs when uploading image to storage`,
    stack: error
   });
  });
  stream.on('finish', () =>
  {
   resolve({
    message: `Image uploaded succesfully.`,
    result: fileId
   });
  });
  stream.end(base64);
 });
}

await upload();

[OUTPUT]
{
 message: `Image uploaded succesfully.`,
 result: fileId
}
```

### Run async/await inside Promise for Stream Based Async Action

In stream based async action, how we run async/await instead of promise inside promise? Just apply async to Promise.

```js
async function log()
{
 console.log('ABC');
}

async function run()
{
 return new Promise(async (resolve, reject) =>
 {
  await log();
  await log();
  resolve('CBA');
 });
}

await run();

[OUTPUT]
ABC
ABC
CBA
```

### Stream based async action codeblock work with ReactiveX

Since reactiveX is popular in many language and useful to development so as RX said they used stream like so you able apply stream based async action code block work with ReactiveX library code also.

```js
async function run()
{
 return new Promise((resolve, reject) =>
 {
  setTimeout(() => {
   resolve('Is me')
  }, 1000);
 });
}

await run();

[OUTPUT]
Is me  // <-- after 1000ms
}

function sample2() {
 return new Promise(resolve => resolve('ABC'));
}

await sample1();
await sample2();

[OUTPUT]
ABC
ABC
```

### Running async operation in a row

As example above all of the action run seperately but you also able to let them run parallel by using build in function `Promise.all`.

```js
async function a()
{
 return "I'm Oska";
}

async function b()
{
 return "I'm student in MMU";
}

async function c()
{
 return "I'm a developer";
}

async function run()
{
 // Promise.all returning array of results so you can either use one of them.
 /* (1) */ const [first, sec, third] = await Promise.all([a(), b(), c()]);
 /* (2) */ const results = await Promise.all([a(), b(), c()]);

 console.log(`${first} ${sec} ${third}`);
 /* OR */
 console.log(`${results[0]} ${results[1]} ${results[2]}`);
}

await run();

[OUTPUT]
I'm Oska
I'm student in MMU
I'm a developer
```

Thanks for your time for looking. Have a nice day.

Popular posts from this blog

Backend Developer & Development [ Part 1 ]

Backend developer is a develop who maintain the work users /  clients can't see such as processing transaction, data structure, data transfer. These works would contains in a API server and API server contains many endpoint that can call by anyone but only success when fulfill endpoint requirements so it is secured. API Server also know as REST API ( Representational State Transfer ). It's processing like client request to server & after server process return response to client. API Server is develop by backend developer and this api server can be many type and different language, different framework such as Ruby on Rails ( RoR ) using Ruby Python PHP ( Laravel & Yii2 ) Java ( Spring ) C# ( ASP.NET & NancyFX ) Node.JS ( ExpressJS, SailsJS, HapiJS, NestJS, FeatherJS ) Different framework have their own advantages and can be used on different projects based on their features and usage. In the development not only choosing frameworks also need to ch...

Local Development | LAN [ Local Area Network ]

Before an application, website, backend server, frontend app or any application required to integrate with another platform, how you work with your friends? Put all in one computer for testing?  Upload to a free hosting for testing like Heroku ? If your team able to work in same place, i would suggest hosted own local network for testing at least faster then using other free platform like Heroku. As of improvement of technology, nowadays network interface card ( NIC ) would have a feature about HostedNetwork. You can host your local area network ( LAN ) for your friends and they can access your works and testing at their own computer and fix would faster the development. In Windows You can use command prompt and type "netsh wlan show drivers" and check is "Hosted network supported : ". If supported you can create your local area network by using command "netsh wlan set hostednetwork mode= allow ssid= YourAP key= YourPW ". YourAP  = Acc...

Coming back to MinecraftAPI

A long time for stop developing minecraft plugins due to busy about university and side works. Coming back from a long learning journey, i decide to recode my personal minecraft api for upcoming new server. Found that the code now i can build it with more structural design pattern. Such as MinecraftAPI interface class for runtime reloadable content. package me.oska.core.abs; public interface MinecraftAPI { void register(); void unregister(); void intialise(); void teardown(); } Also i have updated my reader utility code for reading jar class with functional interface make it more flexible. package me.oska.core.util; import me.oska.core.OskaCore; import me.oska.core.lambda.VoidAction; import org.apache.commons.io.FilenameUtils; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class ReaderUtil { public static void readJAR(File fold...