Javascript Asynchronous, Callback, Promise and Async/Await questions

What are callback functions and provide a simple example ?

Callback is just a function that is passed as an argument to another function. Also as known higher-order function. The callback should be invoked whenever the asynchronous task is finished. Callback functions are not asynchronous. The callback just allows you be informed when the asynchronous task has completed and handles the success or failure of the task.

Why do we even need Callback in Javascript ?

In order to deal with asynchronous operations, we can use Callbacks to inform the user when the task has completed.

What is a Promise ?

Promise is introduced in ES6 to resolve the callback hell issue and handle asynchronous operations. It is an object that might return a value in the future. It accomplishes the same basic goal as a callback function, but with many additional features and a more readable syntax. A promise is an asynchronous action that may complete at some point and produce a value. It is able to notify anyone who is interested when its value is available.

What are the solutions to solve the Callback hell ?

  • Using Promises
  • Using async/await

How Promises resolves Callback hell ?

Promises make callback hell much easier to manage instead of the nested callbacks.

What are Promises used for ?

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

What are the benefits of Promises ?

  1. Improves Code Readability
  2. Better handling of asynchronous operations
  3. Better flow of control definition in asynchronous logic
  4. Better Error Handling

How to combine multiple Promises ?

There are several ways that multiple Promises can be combined:

  • The most important one is the then() method of a Promise. This is the way of Promises are sequenced.
  • Another method is Promise.all() which is used to create a single Promise from multiple independent Promises.
  • The final method is Promise.race() which is similar to Promise.all() .

What are the async/await keywords used for ?

The asyn/awaitkeywords are used to allow developers to write code that feels very much like sequential code but that is still asynchronous. async functions still use promises under the hood, but have a more traditional JavaScript syntax. Using async keyword before the function marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.

async function getUser() {
const response = await fetch('https://api.github.com/users/octocat')
const data = await response.json()
console.log(data)
}
// Execute async function
getUser()

With promise:

// Fetch a user from the GitHub API
fetch('https://api.github.com/users/octocat')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.error(error)
})

Can you print the letters A, B, C in that order in callback , Promise , Async / Await ?

With callbacks:

function printString(string, callback) {  
setTimeout(() => {
console.log(string)
callback()
},1 * 1000)
}
function printAll() {
printString("A", () => {
printString("B", () => {
printString("C", () => {
})
})
})}
printAll()

With promises:

function printString(string) { 
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(string)
resolve()
}, 1 * 1000)})
}
function printAll() {
printString("A").then(() => {
return printString("B")
}).then(() => {
return printString("C")
})
}
printAll()

With async/await :

function printString(string) { 
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(string)
resolve()
}, 1 * 1000)})
}
async function printAll() {
await printString("A")
await printString("B")
await printString("C")
}
printAll()

What will the output be in the following code snippet ? (Multiple .catch’s)

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

Output is print message twice .

What will the output be in the following code snippet ? (Multiple .catch’s)

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))

Output is UnhandledPromiseRejectionWarning.

What will the output be in the following code snippet ? (Chaining .then and .catch’s)

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

Output is print error and undefined .

What will the output be in the following code snippet ? (Chaining .catch’s)

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

Output is print error and undefined .

What will the output be in the following code snippet ?

new Promise((resolve, reject) => {
resolve('Success!')
})
.then(() => {
throw Error('Oh noes!')
})
.catch(error => {
return "actually, that worked"
})
.catch(error => console.log(error.message))

Output is Nothing prints .

What will the output be in the following code snippet ?

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

Output is print SUCCESS .

What will the output be in the following code snippet ?

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

Output is print “SUCCESS" and ”SUCCESS” .

What will the output be in the following code snippet ?

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

Output is prints undefined .

What will the output be in the following code snippet ?

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))

Output is The fails .