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

Flutter codebase sharing

# Clone For master branch come with example, you can clone and run `flutter doctor && flutter run` ``` git clone --single-branch --branch master https://github.com/Oskang09/Flutter-CB2019.git ``` For codebase branch just empty codebase, but setup done you can just start your development. ``` git clone --single-branch --branch codebase https://github.com/Oskang09/Flutter-CB2019.git ``` # Plugins * Dart as "Programming Language" * Flutter as "SDK" * Redux as "State Management" * Fluro as "Navigator Router" # pubspec.yaml ```yaml name: flutter_codebase description: A new Flutter project. version: 1.0.0+1 environment: sdk: ">=2.0.0-dev.68.0 (); Router router = Router(); routers.forEach( (route) { router.define( route.routePath, handler: Handler( handlerFunc: (context, params) => route.widget(params) ), transitionType: route.transitionType ...

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

Object & Container Object

Object / Class What is Object? Object can be people, can be animal, can be anything. Object only store his own data, attributes and property like house has price, size and animal has age and gender.  Object also store his own function or method like animal can eat(); and people can walk();. Try imagine an object is a people, what should it have and what should it don't have? Let's take this example. public class People { private: String name; int age; int hungry; public: void grow() { this->age += 1; } void eat() { hungry = false; } } People can eat, people will grow up so this is true but you try imagine a people can fly(); ? What other programmer see when want to use ur code? "WTF, WTF is this? Oh my godness." so just store whatever the object need, have is enough. When some attribute is too much and enable to split to another object,...