DEV Community

Ayanabilothman
Ayanabilothman

Posted on

6

Write promises chaining using async/await.

First of all, if you don't know anything about JavaScript promises, go through πŸ‘‰ JavaScript promises are simple πŸ‘ˆ article and enjoy code writing using promises πŸ€—

async and await are JavaScript keywords that enable us to work with promises in a more simple way.

async

If you define a function that returns a promise, and this promise will always only resolve, in this case, instead of constructing a promise, you can use async keyword before the function and directly return the resolved value.

Let's clarify by an example πŸ‘‡

Image description

You can replace the second function with the first one. Using async keyword before the function will make this function return an implicit promise behind the scenes. The value you actually return from this function will act as if it is a result passed through hidden resolve function.

And in turns, we can use chaining on the returned promise.

Image description

What about await keyword ?

await

await keyword is used instead of then function, which means we can let go of writing chains.

Image description

Be careful about πŸ€“

  1. await keyword must be used before promises, you can't await for anything expect promise.

  2. await keyword must be used inside a function with async keyword.

Summary:

  • async replaces constructing promises.
  • await replaces then.
  • async can be used alone, but await must be used inside async function.

Error handling of promises is a great topic. It will be clarified in another article, just wait for it πŸ”₯.

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started