Monday, January 24, 2022

fibonacci series of first 10 element

                 int f1 = 0, f2 = 1;

int f3 = 0;

System.out.print(f1+" ");

System.out.print(f2+" ");

for (int i = 1; i <=8; i++) {

f3 = f1 + f2;

System.out.print(f3+" ");

f1 = f2;

f2 = f3;

}

Sunday, January 23, 2022

frequency of integer

 package arrayoperations;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

public class MainApp {

public static void main(String[] args) {

int[] a = { 1, 2, 2, 3, 4, 4, 4 };

Map<Integer, Integer> frequency = new HashMap();

for (int i = 0; i < a.length; i++) {

if (frequency.containsKey(a[i])) {

frequency.put(a[i], frequency.get(a[i]) + 1);

} else {

frequency.put(a[i], 1);

}

}

Set<Integer> keySet = frequency.keySet();

for(Integer i: keySet) {

System.out.println("item: "+ i+ " frequency: "+frequency.get(i));

}

}

}

Tuesday, January 11, 2022

fetch() web API to load data from server

 fetch

    ('https://crossorigin.me/https://www.metaweather.com/api/location/2487956/')

    .then(result => {

        console.log(result);

        return result.json(); //fetch () will return a promise and converting to json object

    })

     .then(data=>console.log(data))

    .catch(error => {

        console.log(error);

    });

here https://crossorigin.me is used to prevent same origin policy.

Wednesday, January 5, 2022

Ajax

 


Ajax is used to load data from the server asynchoronously  without reloading the entire page 
using http get request . Ajax also used to send data using http post request. 

Tuesday, January 4, 2022

How to consume promise when returning a resolved value

 const ids = new Promise((resolve, reject) => { //promise 1

    setTimeout(() => {

        resolve([100, 200, 300, 400, 500]);

    }, 1500);

});

const getReceipe = recId => {  //promise 2

    return new Promise((resolve, reject) => {

        setTimeout(id => {

            const receipe = {

                title: 'potato',

                publisher: 'jonas'

            };

            resolve(`${id}:${receipe.title}`);

        }, 1500, recId);

    });

};


async function getReceipeAW() {

    const allIds = await ids; // here ids is the promise . await keyword is used to wait 

                                          //until the promise resolved

    console.log(allIds);

    const receipe = await getReceipe(allIds[2]);

    console.log(receipe);

    return receipe;

}

getReceipeAW().then(result=>{   // here getReceipeAW() will return a promise then

                                                      //  we need to consume it.

    console.log(`${result} is the best food ever`);

})

Async and await

First, problem without async/await:-

Imagine:

  1. Get user from server
  2. Get orders using user id
  3. Get payment using order id

Using Promise chaining:

getUser()
.then(user => {
return getOrders(user.id);
})
.then(orders => {
return getPayment(orders[0].id);
})
.then(payment => {
console.log(payment);
});

Works fine, but lots of .then().

Same thing:

async function getData() {
const user = await getUser();
const orders = await getOrders(user.id);
const payment = await getPayment(orders[0].id);

console.log(payment);
}

Looks like normal code.

What does async do?

async = This function will return a Promise.

async function hello() {
return "Hi";
}
is equivalent to 
function hello() {
return Promise.resolve("Hi");
}
What does await do?
“Wait here until Promise finishes, then give me the result.”

One important rule:

await only works inside an async function.

❌ Wrong:

const data = await getUser();

✅ Correct:

async function test() {
const data = await getUser();
}
Promise  = "I will give result later"
async = "This function returns a promise"
await = "Wait until promise finishes"

Sunday, January 2, 2022

Promise chaining

Promise chaining means executing multiple asynchronous tasks one after another, where the result of one Promise is used in the next Promise.

Simple idea:

Task-1 finishes

Use result for Task-2

Task-2 finishes

Use result for Task-3

Example:

Get user from server

Using user id, get user orders

Using order id, get payment details

Step 1: Get User

function getUser() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
id: 1,
name: "Lokman"
});
}, 1000);
});
}

This sends:

{ id: 1, name: "Lokman" }

Step 2: Get Orders using User ID

function getOrders(userId) {
return new Promise((resolve, reject) => {

setTimeout(() => {
resolve({
orderId: 101,
product: "Laptop"
});
}, 1000);
});
}

This sends:

{ orderId: 101, product: "Laptop" }

Step 3: Get Payment using Order ID

function getPayment(orderId) {
return new Promise((resolve, reject) => {

setTimeout(() => {
resolve("Payment successful");
}, 1000);
});
}

Promise Chain

getUser()
.then(user => {
console.log(user);
return getOrders(user.id); // return Promise 2
})
.then(order => {
console.log(order);
return getPayment(order.orderId); // return Promise 3
})
.then(payment => {
console.log(payment);
})
.catch(error => {
console.log(error);
});

Saturday, January 1, 2022

Promises in javascript

A Promise is an object that represents the future result of an asynchronous operation.

Example: API call, file reading, database query.

Promise  states -

1. Pending → still waiting
2. Fulfilled → completed successfully
3. Rejected → failed

Example:

const promise = new Promise((resolve, reject) => {

let success = true;

if(success){
resolve("Task completed");
} else {
reject("Task failed");
}
});

Here:

  • resolve() → marks promise as fulfilled
  • reject() → marks promise as rejected 

    To handle the result:

    promise
    .then(result => {
    console.log(result);
    })
    .catch(error => {
    console.log(error);
    });
    • .then() → runs if success
    • .catch() → runs if error










    





Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...