1588377540
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
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);
}
}
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
1600929360
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:
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
1619272838
Explained in detail about
Dont miss to watch the video & ask your questions or doubts in comments
#javascript #async #await
1589255577
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
1636175760
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
1598637660
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.
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.
function sayHello() {
return 'Hello World!';
}
sayHello(); // Hello World!
Copy
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