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

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...

Preparing some plugins for upcoming server

Since i still having a free server from mine friends who in Taiwan keep supporting me for server hosting. For long time busy, and he hope i would still operate and having a survival server so i coming to build up a survival server that not like before only enhance survival gameplay instead of new gameplay and make player doesn't even know how to play. Here come with some idea before i preparing: Custom Building Structure ( Make player easier for some basic works ) Custom PvP & PvE Mechanic ( Make item flexible with skill system and update-able, also work with entity ) Socialize Gamplay ( Guilds & Friends & Party & Mail System ) Daily Gameplay ( Questing, Events )  Any suggestion would be appreciated ( welcome to inbox me :] ) Some images about mine developments in these 2 days. Mine Structure API Skill API work with Items system & Status system And here is the video about the Custom Building Structure Part. As past exp...

Global Game Jam @ 2019 January 25 - 27 with Friends

A 3 day 2 night game development event, Global game jam and held at KDU Glenmarie. With a team of 3 people, we haven't done our game until the end but we learned much on the development. Such as modeling, coding, designing, editing using software like photoshop, magicavoxel, unity. Due to inexperienced we doesn't allocate work properly and lastly only done modeling & some mechanic part like health, damage, team check. But still many mechanic haven't done like taming, spawning and more. Sadly doesn't meet our expectation but really enjoy when developing in this event, KDU's student also very friendly to we. Thanks for the all participate for sharing in this event. Event & Game Information This global game jam event title is about "What is home means to you". So we have come with idea bring characters ( player ) back to home, or with defensive feature also dialog chat. Lastly we decide with Realtime-Strategy Defensive Game ( RTS Defensive ) abo...