///PROMISES in JS /// PROMISE MEANS A TASKS WILL COMPLETED BUT NOT IMMEDIATELY--> //they're 3 states of the promises PENDING , FULFILLLED , REJECTED --> import { log } from "console"; // PROMISE CREATION /////// 1 WAY const promiseOne = new Promise(function(resolve, reject){ //Do an async task // DB calls, cryptography, network setTimeout(function(){ console.log('Async task is compelete'); resolve() /// this is to connnect the than function }, 1000) }) promiseOne.then(function(){ console.log("Promise consumed"); })/// than -> resolve /// 2 way new Promise(function(resolve, reject){ setTimeout(function(){ console.log("Async task 2"); resolve() }, 1000) }).then(function(){ console.log("Async 2 resolved"); }) // 3 way const promiseThree = new Promise(function(resolve, reject){ setTimeout(function(){ resolve({username: "Chai", email: "chai@example.com"}) }, 1000) }) promiseThree.then(function(user){ console.log(user); }) /// 4 way const promiseFour = new Promise(function(resolve, reject){ setTimeout(function(){ let error = true if (!error) { resolve({username: "hitesh", password: "123"}) } else { reject('ERROR: Something went wrong') } }, 1000) }) promiseFour .then((user) => { console.log(user); return user.username }) .then((username) => { console.log(username); }) .catch(function(error){ console.log(error); }) .finally(() => console.log("The promise is either resolved or rejected")) /// 5 way const promiseFive = new Promise(function(resolve, reject){ setTimeout(function(){ let error = true if (!error) { resolve({username: "javascript", password: "123"}) } else { reject('ERROR: JS went wrong') } }, 1000) }); async function consumePromiseFive(){ // async will wait untyill the task gets complete try { const response = await promiseFive console.log(response); } catch (error) { console.log(error); } } consumePromiseFive() // async function getAllUsers(){ // try { // const response = await fetch('https://jsonplaceholder.typicode.com/users') // const data = await response.json() // console.log(data); // } catch (error) { // console.log("E: ", error); // } // } //getAllUsers() fetch('https://api.github.com/users/hiteshchoudhary') .then((response) => { return response.json() }) .then((data) => { console.log(data); }) .catch((error) => console.log(error))