DEV Community

Cover image for Interview Questions About Promises
Syeda Umme Kulsoom
Syeda Umme Kulsoom

Posted on

Interview Questions About Promises

~~~~## Q1
What are Promises?
In the world of JavaScript, promises are your go-to solution for handling asynchronous operations. But what exactly are promises? Well, think of them as placeholders for values that are not yet known. They represent the eventual completion or failure of an asynchronous operation and allow you to handle its result asynchronously.

Imagine you're waiting for a package delivery. You don't know exactly when it will arrive, but you're certain it will eventually either show up at your doorstep or encounter some delivery issues. Promises work similarly—they represent the future outcome of an operation, be it successful or unsuccessful.


States of Promises

  1. Pending
  2. Resolved
  3. Rejected

Q2:Sleep Function

Synatx

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))

}
Enter fullscreen mode Exit fullscreen mode

Solution To Callback hell
_In order to convert callback based function into promise based wrap the callback fucntion into promise and [ass] the handlers resolve and reject ,and you can call the resolve function after successfull completion of the asynchronouse operation _

Lets take an example

Q3

Callback Function

function getdata(dataid,getnextdata){
  setTimeout(()=>{
    console.log("data",dataid)
    if(getnextdata){
      getnextdata()}

  },2000)
}

Enter fullscreen mode Exit fullscreen mode

Promise Function

function getdata(dataid, getnextdat) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("data", dataid)
      resolve("success")
    }, 2000)
    if (getnextdat) {
      getnextdat()
    }

  })

}
Enter fullscreen mode Exit fullscreen mode

Q4

Promise Chaining

const fetchPromise = fetch(
  "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);

fetchPromise.then((response) => {
  const jsonPromise = response.json();
  jsonPromise.then((data) => {
    console.log(data[0].name);
  });
});

Enter fullscreen mode Exit fullscreen mode

Code By MDN WEB DOCS[How to use Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)


That's It
fOLLOW ME for more [LINKEDIN ACCOUNT](https://www.linkedin.com/in/syeda-umm-e-kulsoom-259001268/)

Top comments (0)