0% found this document useful (0 votes)
6K views

Async Javascript

The document discusses asynchronous JavaScript. It covers native async functions like setTimeout and setInterval, promises, async/await, and examples of using promises and async/await for asynchronous code.

Uploaded by

Shashank Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6K views

Async Javascript

The document discusses asynchronous JavaScript. It covers native async functions like setTimeout and setInterval, promises, async/await, and examples of using promises and async/await for asynchronous code.

Uploaded by

Shashank Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Session 5: Async Javascript

1. What are 2 native functions to run code asynchronously in


JavaScript?
a. timeout, startInterval
b. setTimeout, setInterval
c. delay, repeat
d. interval, startInterval

2. What is the function to stop an interval timer?


a. stopTimer
b. clearTimer
c. clearInterval
d. shutDownTimer

3. Node JS example, what will be the output

let fs = require('fs');

console.log('1');

fs.readFile('test.txt', 'utf8', function(error, data) {


if (error) {
throw error;
}

console.log('2');
});

console.log('3');

a. 123
b. 321
c. 231
d. 132

Notes Complied by DHANUSH MUKHI


4. Consider the following async function and its output. What will be
displayed to the console when calling the ​f()​ function?

async function f() {


let result = 'first!';
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('done!'), 1000);
});
result = await promise;
console.log(result);
}
f();

a. first!
b. done!
c. Javascript error
d. Something else

5. What will be the output?

let x = 0;
async function test() {
x += await 2;
console.log(x);
}
test();
x += 1;
console.log(x);

a. 21
b. 1 undefined
c. 12
d. null 1

Notes Complied by DHANUSH MUKHI


6. Async Await simplifies the following?
a. The behaviour of using promises synchronously
b. Callback hell
c. Execution of async code
d. All of the above

7. What will be the output?

async function errorExample() {


try {
const rejectedPromise = await Promise.reject("Oh-oh!");
} catch (error) {
console.log(error); // "Uh-oh!"
}
}
errorExample();

a. error
b. Oh-oh
c. Undefined
d. Null

8. Determine what will be the output?


var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
p.catch(error => console.log(error.message))
p.catch(error => console.log(error.message))

a. Print error message once


b. Print error message twice
c. UnhandledPromiseRejectionWarning
d. Process exits

Notes Complied by DHANUSH MUKHI


9. Determine what will be the output?
var p = new Promise((resolve, reject) => {
return Promise.reject(Error('The Fails!'))
})
p.catch(error => console.log(error.message))
p.catch(error => console.log(error.message))

a. Print error message once


b. Print error message twice
c. UnhandledPromiseRejectionWarning
d. Process exits

10. Determine what will be the output?


var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
.catch(error => console.log(error))
.then(error => console.log(error))

a. Print error and undefined


b. Print error twice
c. UnhandledPromiseRejectionWarning
d. undefined

11. Determine what will be the output?


var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
.catch(error => console.log(error.message))
.catch(error => console.log(error.message))

a. Print error message once


b. Print error message twice
c. UnhandledPromiseRejectionWarning
d. Process exits

Notes Complied by DHANUSH MUKHI


12. Determine what will be the output?
new Promise((resolve, reject) => {
resolve('Success!')
})
.then(() => {
throw Error('Oh noes!')
})
.catch(error => {
return "actually, that worked"
})
.catch(error => console.log(error.message))

a. Print error message once


b. Print error message twice
c. UnhandledPromiseRejectionWarning
d. Nothing prints

13. Determine what will be the output?


Promise.resolve('Success!')
.then(data => {
return data.toUpperCase()
})
.then(data => {
console.log(data)
})

a. Success SUCCESS
b. SUCCESS
c. Success
d. Nothing prints

Notes Complied by DHANUSH MUKHI


14. Determine what will be the output?
Promise.resolve('Success!')
.then(data => {
return data.toUpperCase()
})
.then(data => {
console.log(data)
return data
})
.then(console.log)

a. SUCCESS SUCCESS
b. SUCCESS
c. Success
d. Nothing prints

15. Determine what will be the output?

Promise.resolve('Success!')

.then(data => {

data.toUpperCase()

})

.then(data => {

console.log(data)

})

a. SUCCESS SUCCESS
b. SUCCESS
c. Success
d. Nothing prints

Notes Complied by DHANUSH MUKHI


16. Determine what will be the output?

Promise.resolve('Success!')
.then(() => {
throw Error('Oh noes!')
})
.catch(error => {
return 'actually, that worked'
})
.then(data => {
throw Error('The fails!')
})
.catch(error => console.log(error.message))
a. Oh noes! , The fails!
b. Oh noes!
c. The fails!
d. Nothing prints

17. ​What are the different ways to deal with Asynchronous Code

Below are the list of different ways to deal with Asynchronous code.

i. Callbacks
ii. Promises
iii. Async/await
iv. Third-party libraries such as async.js, bluebird etc

18. What are asynchronous thunks?

The asynchronous thunks are useful to make network requests. Let's see an
example of network requests,

Notes Complied by DHANUSH MUKHI


function fetchData(fn){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => fn(json))
}
const asyncThunk = function (){
return fetchData(function getData(data){
console.log(data)
})
}
asyncThunk()

19. ​What are the three states of promise?

Promises have three states:

i. Pending: This is an initial state of the Promise before an operation


begins
ii. Fulfilled: This state indicates that the specified operation was
completed.
iii. Rejected: This state indicates that the operation did not complete. In
this case an error value will be thrown.

20. ​What is callback hell?

Callback Hell is an anti-pattern with multiple nested callbacks which makes


code hard to read and debug when dealing with asynchronous logic. The
callback hell looks like below,

Notes Complied by DHANUSH MUKHI


async1(function(){

async2(function(){

async3(function(){

async4(function(){

....

});

});

});

});

Code used for explanation of Callbacks, promises, async await

consts Posts = [{title: "One", body: "Body num 1"},

{title: "Two", body: "Body num 2"}];

function getPosts(){

setTimeout(() => {

let output = '';

posts.forEach((post, index)=> {

output += `<li> ${post.title, post.body} </li>`

});

document.body.innerHTML = output;

}, 1000);

// Callbacks

/*function createPost(post, callback){

Notes Complied by DHANUSH MUKHI


setTimeout(()=> {

posts.push(post);

callback();

}, 2000);

//createPost({title: "Three", body: "body num 3"}, getPosts);

// promises

function createPost(post){

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

setTimeout(()=>{

posts.push(post);

const error =false; // catch only if error is true

if(!error){

resolve();

else{

reject(Error(""h

}, 2000)

})

createPost({title: "Three", body: "body num 3"})

.then(getPosts)

Notes Complied by DHANUSH MUKHI


.catch(err => console.log(err))

// promise.all

const p1 = Promise.resolve("name");

const p2 = 10;

const p3 = new Promise((resolve, reject)=> setTimeout(resolve, 2000, "Hello"));

const p4 = fetch("api url").then(res => res.json());

Promise.all([p1, p2, p3, p4]). then(values => console.log(values))

//async await

async function init(){

await createPost({title: "Three", body: "body num 3"});

getPosts();

init();

O/P:

One Body num1

Two Body num2

Three Body num3

Notes Complied by DHANUSH MUKHI

You might also like