interview community logo

What is a promise
1 answer

What is a promise?

and what is the native alternative if won't use promise?

and how promise is better than the alternative?

JavaScript Robert Isaac asked 1 year ago


a Promise is a value that will be available in the future

a good example is fetch e.g. fetch('').then(res => console.log(res)) when you call fetch the value of the response of the http call isn't available instantly (synchronously aka sync) but will be available in the future (asynchronously aka async)

the alternative is using callback function, equivalent example of fetch is XMLHttpRequest to do the same request this how it would look like

function reqListener() {

const req = new XMLHttpRequest();
req.addEventListener("load", reqListener);"GET", "");

you can see how much boilerplate code is written to do the same basic job, that's one benefit

the other problem with callback hell, which means the more dependent your async code is on each other, the more nested it will be be

e.g. with callback

function example(input) {
  doSomethingAsync1(input, res1 => {
    doSomethingAsync2(res1, res2 => {
      doSomethingAsync3(res2, res3 => {

e.g. with promise

function example(input) {
  doSomethingAsync1(input).then(res1 => {
    return doSomethingAsync2(res1);
  }).then(res2 => {
    return doSomethingAsync3(res2);
  }).then(res3 => {

another benefit with promises is using async function, rewriting the same example with async

async function example(input) {
  const res1 = doSomethingAsync1(input);
  const res2 doSomethingAsync2(res1);
  const res3 = doSomethingAsync3(res2);

you can see how much better and clean the last function is compared to version 1, and the more dependencies you have the last one becomes much better

Robert Isaac answered 12 months ago loading comments...