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

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

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

A long journey before i going back to other platforms

That's a long journey for going work on mine other projects due to i participate a startup mate together work on a startup projects. In the projects, i learn and workaround back-end framework in many of languages ( due to private work cant show too much code ). Also i does self-taught some front-end frameworks by learn from mine front-end mate's code & re-base using flutter . It was taken about half of a year to build up a proper back-end server due to inexperienced of my skills and technique so take time to learn. I have also played around many frameworks such as   Back-end ExpressJS - Most basic of the back-end frameworks NestJS - A progressive Node.js framework for building efficient and scalable server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8) heavily inspired by Angular SailsJS - A MVC framework inspired from Ruby on Rails, have a really good structure and newbie friendly HapiJS - Quite same with Express but more exte