xxxxxxxxxx
// In JavaScript, An async function is a function declared with the async keyword, and the await keyword can then be permitted within it.
// Example;
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
// The asnycCall function when run will wait for the await block which calls resolveAfter2Seconds() before it logs the output to the console.
// We can also use the then method to wait for an async call before running another block of code.
// Example;
async function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
resolveAfter2Seconds().then(
function(result){console.log(result)}
function(error){console.log(result)}
);
// There are so many other ways of writing asychronous functions in javascript.
// Javascript is itself an asychronous language.
xxxxxxxxxx
// example using promise
const user = () => {
fetch("https://randomuser.me/api/?results=1")
.then((data) => {
console.log(data); // here you recive data
}).catch((err)=>{
console.log(err); // here error
});
}
// example using async/await
const user = async () => {
// you must have use async keyword before use await
const data = await fetch("https://randomuser.me/api/?results=1");
console.log(data); // if error occured it will be null or empty
}
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
// example of async and await in javascript
// First create promise
let myPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Yay, I resolved!')
}, 1000);
});
}
// async without await keyword
async function noAwait() {
let value = myPromise();
console.log(value);
}
// async with await keyword
async function yesAwait() {
let value = await myPromise();
console.log(value);
}
noAwait(); // Prints: Promise { <pending> }
yesAwait(); // Prints: Yay, I resolved!
xxxxxxxxxx
//used in node.js
const fetch = require('node-fetch');
async function Showuser() {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const date = await result.json();
console.log(date);
}
Showuser();
xxxxxxxxxx
function delayResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve(‘Done’);
}, 5000)
})
}
async function getResult() {
let result = await delayResult();
return result;
}
getResult();
simple use case of async function in javascropt
xxxxxxxxxx
async function logFetch(url) {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('fetch failed', err);
}
}
xxxxxxxxxx
async function showAvatar() {
// read
await setTimeout(resolve, 3000);
// read next 3s
}
showAvatar();
xxxxxxxxxx
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
// catches errors both in fetch and response.json
alert(err);
}
}
f();