// 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
}
const yourAsyncFunction = async () => {
// do something asynchronously and return a promise
return result;
}
anArray.forEach(async item => {
// do something asynchronously for each item in 'anArray'
// one could also use .map here to return an array of promises to use with 'Promise.all()'
});
server.getPeople().then(async people => {
people.forEach(person => {
// do something asynchronously for each person
});
});
//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();
// ASYNC will always returns promises
// NOTE : AWAIT should be kept only inside ASYNC function
// AWAIT can't be used in regular function
/* TIPS : Js is single threaded & synchronous in nature BUT, we can
make it as asyncronous by using (ASYNC/AWAIT)*/
//(Example 1 : fetching Random Image)
async function RandomImage(){ //remember async and await is powerful for async operations, always await should be inside of async only.
try {
const raw_response = await fetch("https://www.themealdb.com/api/json/v1/1/random.php");
if (!raw_response.ok) { // check for the 404 errors
throw new Error(raw_response.status);
}
const json_data = await raw_response.json(); //AWAIT
let data = json_data.meals[0];
console.log(data);
}
catch (error) { // catch block for network errors
console.log(error);
}
}
RandomImage();
//(Example 2 : returning another promise)
console.log("1 is working");
console.log("2 is working");
var AsyncFunction = async() => {
var x = new Promise((resolve,reject) => {
setTimeout(() => resolve("3 is working"), 3000);
});
var result = await x;
return result;
}
AsyncFunction().then(resolved => console.log(resolved));
console.log("3 is working");
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();
//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!
}
// 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!