Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

completed javascript assignment 8 #8

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Q1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
1. Write a function that can stop execution of a function for the number of
milliseconds sent as an argument
Example:
const func = async () => {
console.log(“Printing before”)
//Call your function here eg. sleep(3000)
console.log(“Printing after”)
}
*/

const func = async (time) => {
console.log("Printing before");
setTimeout(() => {
console.log(`Executed after ${time} seconds`);
}, time);
console.log("Printing after");
};

func(5000);
31 changes: 31 additions & 0 deletions Q2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
2. Using promises - write a function that fetches data from an API endpoint
(GET https://reqres.in/api/users ).
Log the data into the console once it is received
*/

//with await
async function getUsers(url) {
let response = await fetch(url);
return response.json();
}

let users = getUsers("https://reqres.in/api/users ");
users.then((result) => {
console.log(result);
});

//without await
function getUsersWithoutAwait(url) {
fetch(url)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => err);
}

//this gives required data
getUsersWithoutAwait("https://reqres.in/api/users ");

//this gives Promise { <pending> }
//Bcoz of JS Engine-> log function gets executed first, before even the promise resolves
// console.log({ users });
47 changes: 47 additions & 0 deletions Q3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
3. What will be printed to the console when the promise resolves and when it rejects?
const testAsyncFunction = () =>{
return new Promise((resolve, reject) =>{
if (Math.random() > 0.5) {
resolve('Test Resolve');
} else {
reject('Test Reject');
}
}).catch((err) =>{
console.log('Error caught in testAsyncFunction: ', err);
});
};
testAsyncFunction()
.then((res) =>{
console.log('Response in then block: ', res);
})
.catch((err) => console.log('Error in catch block: ', err));
*/

const testAsyncFunction = () => {
return new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve("Test Resolve");
} else {
reject("Test Reject");
}
}).catch((err) => {
console.log("Error caught in testAsyncFunction: ", err);
});
};

testAsyncFunction()
.then((res) => {
console.log("Response in then block: ", res);
})
.catch((err) => console.log("Error in catch block: ", err));

//When the promise resolves, we get - "Response in then block: Test Resolve"
//As parameter passed in resolve function gets passed in then function of promise.

//When the promise rejects, we get -
//Error caught in testAsyncFunction: Test Reject
// Response in then block: undefined

//As we have written catch in the function itself the error gets executed there
//and in the next catch it returns undefined. So we get result as above
25 changes: 25 additions & 0 deletions Q4.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
4. What will be printed to the console?
const testAsyncFunction = () =>{
return Promise.reject('Test static reject');
};
testAsyncFunction()
.then((res) =>{
console.log('Response in then block', res);
})
.catch((err) => console.log('Error in catch block', err));
*/

const testAsyncFunction = () => {
return Promise.reject("Test static reject");
};
testAsyncFunction()
.then((res) => {
console.log("Response in then block", res);
})
.catch((err) => console.log("Error in catch block", err));

//Output-Error in catch block Test static reject

//The static Promise.reject function returns a Promise that is rejected.
//It is a generic method
55 changes: 55 additions & 0 deletions Q5.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
5. What will be printed to the console?
const testAsyncFunction = () =>{
return new Promise((resolve, reject) =>{
if (Math.random() > 0.5) {
resolve('Test Resolve');
} else {
reject('Test Reject');
}
}).catch((err) =>{
console.log('Error caught in testAsyncFunction', err);
throw new Error('Forced error');
});
};
testAsyncFunction()
.then((res) =>{
console.log('Response in then block: ', res);
})
.catch((err) => console.log('Error in catch block: ', err));

*/

const testAsyncFunction = () => {
return new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve("Test Resolve");
} else {
reject("Test Reject");
}
}).catch((err) => {
console.log("Error caught in testAsyncFunction", err);
throw new Error("Forced error");
});
};
testAsyncFunction()
.then((res) => {
console.log("Response in then block: ", res);
})
.catch((err) => {
console.log("Error in catch block: ", err);
});

//When promise resolves-
//Output:-Response in then block: Test Resolve

//When promise rejects-
/*Output:-Error caught in testAsyncFunction Test Reject
Error in catch block: Error: Forced error
at /home/josh/javascript_training/Q5.js:32:11
*/

/*
we have thrown a new error in the function of catch block of previous promise,
which gets catched in the next execution
*/
34 changes: 34 additions & 0 deletions Q6.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Q6. Create a promise that makes a fetch call,
but resolves with the data only 2 seconds after the data
has been received in the fetch.

*/

const getUsers = (url) => fetch(url);

const newFunc = () => {
return new Promise((res, rej) => {
getUsers("https://reqres.in/api/users")
.then((users) => {
if (!users) {
rej("Not Found...");
}
console.log("receivedData");
setTimeout(() => {
res(users.json());
}, 2000);
})
.catch((err) => {
console.log(err);
});
});
};

newFunc()
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
30 changes: 30 additions & 0 deletions Q7.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Q7. Create a promise that makes a fetch call,
but resolves with the data only 2 seconds after the data
has been received in the fetch.
(with async and await)
*/

//With Async and Await

const getUsers = async (url) => await fetch(url);

const func = (url) => {
return new Promise((res, rej) => {
getUsers(url)
.then((users) => {
if (!users) {
rej("Not Found...");
}
console.log("receivedData");
setTimeout(() => {
res(users.json());
}, 2000);
})
.catch((err) => {
console.log("Custom Error ", err);
});
});
};

func("https://reqres.in/api/users").then((users) => console.log(users));