xxxxxxxxxx
(async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
})();
// (BONUS CODE) await with promise
await new Promise(resolve => setTimeout(resolve, 1000))
console.log('Hello!') // 1 seconds after sended console.log
xxxxxxxxxx
The async Keyword
The async keyword is used to write functions that handle asynchronous actions.
We wrap our asynchronous logic inside a function prepended with
the async keyword. Then, we invoke that function.
async function myFunc() {
// Function body here
};
myFunc();
async functions always return a promise. This means we can
use traditional promise syntax, like .then() and .catch
with our async functions. An async function will return in
one of three ways:
1) If there’s nothing returned from the function,
it will return a promise with a resolved value of undefined.
2) If there’s a non-promise value returned from the function,
it will return a promise resolved to that value.
3) If a promise is returned from the function,
it will simply return that promise
Example:
async function fivePromise() {
return 5;
}
fivePromise()
.then(resolvedValue => {
console.log(resolvedValue);
}) // Prints 5
In the example above, even though we return 5 inside the function body,
what’s actually returned when we invoke fivePromise() is a promise
with a resolved value of 5.
// Constructor Method:
function withConstructor(num){
return new Promise((resolve, reject) => {
if (num === 0){
resolve('zero');
} else {
resolve('not zero');
}
});
}
withConstructor(0)
.then((resolveValue) => {
console.log(` withConstructor(0) returned a promise which
resolved to: ${resolveValue}.`);
});
// Async Method:
const withAsync = async (num)=>{
if(num===0) {return 'zero'
}else{
return 'not zero';
}
}
// Now invoking that function
withAsync(100)
.then((resolveValue) => {
console.log(` withAsync(100) returned a promise which
resolved to: ${resolveValue}.`);
})
/*
withAsync() reproduces the
functionality of withConstructor(). Though your function
will return a promise, it should not construct the promise
using the new keyword. Instead, it should rely on the fact
that an async function automatically returns a promise.
*/
The await Operator:
we covered the async keyword. By itself, it doesn’t do much;
async functions are almost always used with the additional
keyword await inside the function body.
The await keyword can only be used inside an async function.
await is an operator: it returns the resolved value of a promise.
Since promises resolve in an indeterminate amount of time,
await halts, or pauses, the execution of our async function
until a given promise is resolved.
In most situations, we’re dealing with promises that were
returned from functions. Generally, these functions are through
a library. We can await the resolution of the promise it returns
inside an async function. In the example below, myPromise()
is a function that returns a promise which will resolve to
the string "I am resolved now!".
Example:
async function asyncFuncExample(){
let resolvedValue = await myPromise();
console.log(resolvedValue);
}
asyncFuncExample(); // Prints: I am resolved now!
/*
Within our async function, asyncFuncExample(),
we use await to halt our execution until myPromise()
is resolved and assign its resolved value to the variable
resolvedValue. Then we log resolvedValue to the console.
We’re able to handle the logic for a promise in a way that
reads like synchronous code.
*/
Handling Dependent Promises:
/*
The true beauty of async...await is when we have a series
of asynchronous actions which depend on one another.
For example, we may make a network request based on a
query to a database. In that case, we would need to
wait to make the network request until we had the results
from the database. With native promise syntax, we use a
chain of .then() functions making sure to return
correctly each one:
*/
// Comparison of two versions:
function nativePromiseVersion() {
returnsFirstPromise()
.then((firstValue) => {
console.log(firstValue);
return returnsSecondPromise(firstValue);
})
.then((secondValue) => {
console.log(secondValue);
});
}
// -------
async function asyncAwaitVersion() {
let firstValue = await returnsFirstPromise();
console.log(firstValue);
let secondValue = await returnsSecondPromise(firstValue);
console.log(secondValue);
}
// The async...await version more closely resembles synchronous
// code, which helps developers maintain and debug their code.
/*
Handling Errors:
With async...await, we use try...catch statements for error
handling. By using this syntax, not only are we able to
handle errors in the same way we do with synchronous code,
but we can also catch both synchronous and asynchronous errors.
This makes for easier debugging!
*/
//Example:
async function usingTryCatch() {
try {
let resolveValue = await asyncFunction('thing that will fail');
let secondValue = await secondAsyncFunction(resolveValue);
} catch (err) {
// Catches any errors in the try block
console.log(err);
}
}
usingTryCatch();
xxxxxxxxxx
const showPosts = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
console.log(posts);
}
showPosts();
xxxxxxxxxx
const foo = async () => {
await// do something
}
// OR
async function foo() {
await// do something
}
xxxxxxxxxx
//ORIGINAL
//each .then() returns a promisse and can be chained. The .then() will run after the previous one has finished. It emulates an async/await behavior.
fetch('https://jsonplaceholder.typicode.com/users')//fetch the content
.then((response) => response.json())//then use that content and convert it to a javascript object
.then(users => {
const firstUser = users[0];
console.log(firstUser);
return fetch('https://jsonplaceholder.typicode.com/posts?userId=' + firstUser.id);
})//then return the content from posts related to that user ID
.then((response) => response.json())//then use that content and convert it to a javascript object
.then(posts => console.log(posts));//then log the result
//ASYNC/AWAIT
const myAsyncFunction = async () => {//define that this will be asynchronous
const usersResponse = await fetch('https://jsonplaceholder.typicode.com/users');//wait for the fecth result and put it in the variable
const users = await usersResponse.json();//wait for the previous item to be done, transform it into a javascript object and put it in the variable
const secondUser = users[1];
console.log(secondUser);//then log the result
const postsResponse = await fetch('https://jsonplaceholder.typicode.com/posts?userId=' + secondUser.id);//wait for the previous item to be done, wait for the fecth result and put it in the variable
const posts = await postsResponse.json();//wait for the previous item to be done, transform it into a javascript object and put it in the variable
console.log(posts);//then log the result
}
myAsyncFunction();
xxxxxxxxxx
//Async function (JAVASCRIPT)
//async function have 1 main purpose:
//Being able to use 'await' in a function
function example() {
return await fetch('https://mysite.com/api'); //error
}
async function smartexample() {
return await fetch('https://mysite.com/api'); //mhmm!
}
xxxxxxxxxx
async function getData() {
const [error, response] ?= await fetch("https://api.example.com/data");
if (error) return handleError(error);
return response;
}
xxxxxxxxxx
function loginUser(email, password) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Now we have the data');
resolve({ userEmail: email });
}, 1500);
});
}
function getUserVidoes(email) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('we got details');
resolve(['HTML', 'CSS', 'JAVASCRIPT']);
}, 1200);
});
}
function videosDetails(video) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('we got single video details');
resolve(`title of the video is ${video} `);
}, 1000);
});
}
async function displayUser() {
try {
const loggedUser = await loginUser('shirshak', 12345);
const videos = await getUserVidoes(loggedUser.user);
const detail = await videosDetails(videos[2]);
console.log(detail);
} catch (err) {
console.log('We could not get videos');
}
}
displayUser();
xxxxxxxxxx
let line =
"Quisque vel rutrum lacus. Morbi sed finibus elit, in dictum nulla. Ut ac fermentum lectus, at molestie leo. Etiam ligula eros, placerat ut mattis at, aliquam ac lectus. Vivamus a ultrices odio. Sed vulputate dapibus sem sit amet imperdiet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi mollis felis pellentesque, bibendum sapien eu, bibendum nunc. Vivamus faucibus, nunc eget dapibus consectetur, diam dolor iaculis mauris, at tristique dui quam at neque. Maecenas ligula ex, ultricies dignissim dui eget, suscipit elementum tellus. Aliquam erat volutpat. Mauris semper quam vitae faucibus accumsan. Duis laoreet auctor tellus, pulvinar elementum est pellentesque ornare. Morbi bibendum scelerisque luctus. Phasellus elementum dignissim sapien sed dignissim.Quisque vel rutrum lacus. Morbi sed finibus elit, in dictum nulla. Ut ac fermentum lectus, at molestie leo. Etiam ligula eros, placerat ut mattis at, aliquam ac lectus. Vivamus a ultrices odio. Sed vulputate dapibus sem sit amet imperdiet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi mollis felis pellentesque, bibendum sapien eu, bibendum nunc. Vivamus faucibus, nunc eget dapibus consectetur, diam dolor iaculis mauris, at tristique dui quam at neque. Maecenas ligula ex, ultricies dignissim dui eget, suscipit elementum tellus. Aliquam erat volutpat. Mauris semper quam vitae faucibus accumsan. Duis laoreet auctor tellus, pulvinar elementum est pellentesque ornare. Morbi bibendum scelerisque luctus. Phasellus elementum dignissim sapien sed dignissim.";
async function CountChar (sentence) {
const count = await sentence.length;
const result = (count * 1000000000); // making a big calculation
console.log(result);
}
CountChar(line); // this will print at the last because its big calculation then other and this is the magic of async function.
// those will print first because and not hold exicution
console.log("I am first");
console.log("I am second");
console.log("I am third");