DEV Community

Cover image for Do you know Promises in JS ? (Basic)
Margish Patel
Margish Patel

Posted on

Do you know Promises in JS ? (Basic)

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

World
Hello
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

output โœ…:

After promise
Error
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Third
First
Second
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Done
Success
Fail
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Immediate
Timeout
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Function
Async
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

End
Finally
Resolved
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Start
Done
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Third
First
Second
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

output โœ…:

Inside function
Outside function
Async
Enter fullscreen mode Exit fullscreen mode

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 ๐Ÿ’ป...

Top comments (0)