Condo Mark

Condo Mark

1588377540

Understanding Async/Await in Javascript | Key Things to Remember

Why use Async/Await?

The reason why I will also prefer async/await is because it makes code so much cleaner and easier to read, especially when you have multiple chaining going on. Readability and maintainability are always on the top of my mind when I am writing code. Your colleague will appreciate your clean code, even if they never mention it!

Key Things to Remember

  • Async/Await is nothing more than syntactic sugar around promises
  • Async functions are functions that return promises
  • Await can only be used inside a function marked async
  • Use try/catch with async functions to catch exceptions

Learn by Example

Personally, one of the best ways for me to learn is through examples. This is why I will keep my explanations short. I am also going to keep my examples super simple and easy to follow.

Simple HTTP Request with Axios

Let’s take a look at a simple function that gets a post from jsonplaceholder using promises.

function getToDo() {
  axios.get('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => console.log(response.data))
    .catch(error => console.error(error))
}

We can rewrite this using async/await like this:

async function getToDo() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
    console.log(response);
  } catch (error) {
    console.log(error);
  }
}

A More Real-World HTTP Request Example

Here is a snippet from a project I recently worked on. Superagent is lightweight http library similar to Axios. The getCustomer function is making a HTTP request and setting Authorization headers. Once I receive the response, I set them in my data variables (I am using Vue.js as the frontend framework in this project).

import request from 'superagent';

...

const getCustomer = (id) => {
  request
    .get(`${process.env.CUSTOMERS_ENDPOINT}/customer/${id}`)
    .set('Authorization', this.$store.state.idToken)
    .then(response => {
      this.customers = response.body.userProfiles;
      this.page = response.body.currentPage;
      this.maxPages = response.body.totalPages;
    })
    .catch(err => {
      this.$config.showError(err);
    });
}

...

Now let’s rewrite this to use async/await:

import request from 'superagent';

...

const getCustomer = async (id) => {
  try {
    const response = await request
      .get(`${process.env.CUSTOMERS_ENDPOINT}/customer/${id}`)
      .set('Authorization', this.$store.state.idToken)

    this.customers = response.body.userProfiles;
    this.page = response.body.currentPage;
    this.maxPages = response.body.totalPages;    
  } catch (error) {
    this.$config.showError(error);
  }
}

...

Async/Await with a simple MongoDB Request

Here is an example of a database call to MongoDB with Mongoose using promises.

const db = require('../models');

module.exports = {
  findById: function(req, res) {
    const { id } = req.query;
    
    db.Book.find(id)
      .sort({ date: -1 })
      .then(data => res.json(data))
      .catch(err => res.json(err));
  }
};

Async/Await!

const db = require("../models");

module.exports = {
  findAll: async function(req, res) {
    const { id } = req.query;

    try {
      const books = await db.Book.find(id).sort({ date: -1 });
      res.json(books);
    } catch (err) {
      res.json(err);
    }
  }

Conclusion

My intent here is to keep the article short and sweet. Something that people can use as a reference or guide. As previously mentioned, if you are seeking more in-depth explanations regarding the internal workings of Promises and Async/Await, there are tons of great resources that covers this topic. Thank you!

#javascript #programming

What is GEEK

Buddha Community

Understanding Async/Await in Javascript | Key Things to Remember
Giles  Goodwin

Giles Goodwin

1600929360

Understanding JavaScript: Promises, Async & Await!!

Analogy

We all know the importance of promises in our life. We even have a special day dedicated to it :) But how well do we know the importance of promises in JavaScript? Well if you don’t know it yet, it’s a great time to know it because they are becoming more and more popular. So what are promises? Let’s try to understand it through an analogy.

Suppose you are a top class rapper and you haven’t released an album for a while and fans are asking for it day and night. So what you do is that you “promise” them that whenever it will be out, all of them would be notified. To get this done you give your fans a list. They can fill in their email addresses, so that when the album becomes available, all the subscribers instantly receive it. And even if something goes wrong, say a pandemic, so that you can’t release the album, they will still be notified.

Now everyone is happy: You, because the people don’t crowd you anymore, and fans, because they won’t miss any news on the album.

This is a real-life analogy for things we often have in programming:

  1. “producing code” that does something and may take time. That’s a “rapper”.
  2. “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result. These are the “fans”.
  3. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.

JavaScript promises are much more complex than a simple subscription list: they have additional features and limitations. But it’s fine to begin with.

#async #promises #javascript #development #await

Javascript : Async Await in Javascript | Javascript Interview questions.

Explained in detail about

  • Async
  • Await
  • Fetching country data using Async & Await
  • How Async & Await better than promise

Dont miss to watch the video & ask your questions or doubts in comments

https://youtu.be/pJbsd2vAqdI

#javascript #async #await

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Ollie  Dietrich

Ollie Dietrich

1636175760

How Async/Await Works in Javascript

Async/await is a new way to write asynchronous code.  Async/await is actually just syntax sugar built on top of promises. It makes asynchronous code look and behaves a little more like synchronous code.

 

Thumb Rules for async-await:
1. `async` functions return a promise.
2. `await` pauses the code execution within the `async` function.
3. There can be multiple `await` statements within a single `async` function.
4. `await` only pauses the code execution within the `async` function. It makes sure that the next line is executed when the promise resolves.

 

⌚ Timestamps:
00:00 Introduction
00:58 Async
02:27 Await

 #javascript  #async  #await 

Sadie  Cassin

Sadie Cassin

1598637660

How To Use Async/Await in JavaScript

How To Use Async/Await in JavaScript

SHARE     

Async/Await

The async and await is keywords to perform the promise-based asynchronous operation. In this article, we are going to learn how to use async/await in JavaScript.

How to use Async?

It is mandatory to define the async keyword before any function that turns your normal function to async function. Let’s start to learn it through a very basic example.

Normal Function Example

function sayHello() {
    return 'Hello World!';
}

sayHello(); // Hello World!

Copy

Async Function Example

async function sayHello() {
    return 'Hello World!';
}

sayHello(); // [object Promise] { ... }

Copy

We could explicitly return a promise with Promise.resolve() like:

async function sayHello() {
    return Promise.resolve('Hello World!');
}
async function sayHello() {
    return 'Hello World!';
}

let greeting = sayHello();
greeting.then((value) => console.log(value)); // Hello World!

Copy

or you can try this:

async function sayHello() {
    return 'Hello World!';
}

sayHello().then((value) => console.log(value) ); // Hello World!

#javascript #async #await