Do you know Promises in JS ? (Basic)
Tags: javascript, webdev, programming, interview
Published: 2024-07-04 14:40:32

## Introduction 
Hey forks !
In this blog post, we are going to explore 10 tricky JavaScript questions that test your understanding of Promises and asynchronous behaviour of Javascript.


### What are Promises and how to handle it in JS ? 
- JavaScript Promises are a powerful tool for handling **asynchronous operations**. 
- They represent a value that may be available now, in the future, or never. 
- Promises simplify complex asynchronous code by providing a more readable and maintainable structure. With methods like .then(), .catch(), and .finally(), Promises allow you to chain operations and handle errors gracefully.


- Building on Promises, async and await are syntactic sugar that make asynchronous code look and behave more like synchronous code. 
- The async keyword declares an asynchronous function, which returns **a Promise**, while the await keyword **pauses the execution** until the Promise is resolved. 
- This modern approach simplifies **error handling** and reduces the need for complex Promise chains, making your code cleaner and more maintainable. 


- Understanding Promises and async/await is essential for writing modern, efficient JavaScript code, especially when dealing with APIs, timers, or any asynchronous tasks.



Now let's start solving some basic promise related output based questions which might help you to crack the interviews.

### Example 1: 
Code
```
let p = new Promise((resolve, reject) => {
  resolve("Hello");
});
p.then(value => console.log(value));
console.log("World");

```
output ✅:
```
World
Hello
```
> Explanation 💡: 
- The `console.log("World")` executes immediately.
- The Promise resolves and logs "Hello" after the synchronous code has finished executing.

---

### Example 2: 
Code
```
let p = new Promise((resolve, reject) => {
  reject("Error");
});
p.catch(error => console.log(error));
console.log("After promise");
```
output ✅:
```
After promise
Error
```
> Explanation 💡: 
- The `console.log("After promise")` executes immediately.
- The Promise is rejected and logs "Error" after the synchronous code has finished executing.

---

### Example 3: 
Code
```
let p = new Promise((resolve, reject) => {
  resolve("First");
});
p.then(value => {
  console.log(value);
  return "Second";
}).then(value => console.log(value));
console.log("Third");

```
output ✅:
```
Third
First
Second
```
> Explanation 💡: 

- The `console.log("Third")` executes immediately.
- The Promise resolves and logs "First", then the chained then logs "Second".

---

### Example 4: 
Code
```
let p = Promise.resolve("Success");
p.then(value => {
  console.log(value);
  throw new Error("Fail");
}).catch(error => console.log(error.message));
console.log("Done");

```
output ✅:
```
Done
Success
Fail
```
> Explanation 💡: 
- The `console.log("Done")` executes immediately.
- The Promise resolves and logs "Success", then the error is caught and "Fail" is logged.

---

### Example 5: 
Code
```
let p = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Timeout"), 1000);
});
p.then(value => console.log(value));
console.log("Immediate");

```
output ✅:
```
Immediate
Timeout
```
> Explanation 💡: 
- The `console.log("Immediate")` executes immediately.
- The Promise resolves after 1 second and logs "Timeout".

---
### Example 6: 
Code
```
async function asyncFunc() {
  return "Async";
}
asyncFunc().then(value => console.log(value));
console.log("Function");

```
output ✅:
```
Function
Async
```
> Explanation 💡: 

- The `console.log("Function")` executes immediately.
- The `asyncFunc` resolves and logs "Async" after the synchronous code has finished executing.

---

### Example 7: 
Code
```
let p = new Promise((resolve, reject) => {
  resolve("Resolved");
});
p.finally(() => console.log("Finally"))
 .then(value => console.log(value));
console.log("End");

```
output ✅:
```
End
Finally
Resolved
```
> Explanation 💡: 
- The `console.log("End")` executes immediately.
- The Promise finally logs "Finally" and then logs "Resolved".

---

### Example 8: 
Code
```
async function asyncFunc() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve("Done"), 500);
  });
}
asyncFunc().then(value => console.log(value));
console.log("Start");

```
output ✅:
```
Start
Done
```
> Explanation 💡: 
The `console.log("Start")` executes immediately.
The asyncFunc resolves and logs "Done" after 500ms.
---

### Example 9: 
Code
```
let p = Promise.resolve("First");
p.then(value => {
  console.log(value);
  return Promise.resolve("Second");
}).then(value => console.log(value));
console.log("Third");

```
output ✅:
```
Third
First
Second
```
> Explanation 💡: 
- The `console.log("Third")` executes immediately.
- The Promise resolves and logs "First", then the chained then logs "Second".

---

### Example 10: 
Code
```
async function asyncFunc() {
  console.log("Inside function");
  return "Async";
}
asyncFunc().then(value => console.log(value));
console.log("Outside function");

```
output ✅:
```
Inside function
Outside function
Async
```
> Explanation 💡: 
- The asyncFunc logs "Inside function" immediately.
- The `console.log("Outside function")` executes immediately.
- The asyncFunc resolves and logs "Async" after the synchronous code has finished executing.

---


That’s all from my side, keep practising forks 🔥!!!
🫡See you in next blog.

Happy Coding 💻...