interview community logo

1
0
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 9 months ago


1

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

a good example is fetch e.g. fetch('http://www.example.org/example.txt').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() {
  console.log(this.responseText);
}

const req = new XMLHttpRequest();
req.addEventListener("load", reqListener);
req.open("GET", "http://www.example.org/example.txt");
req.send();

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 => {
        doSomething(res3);
      }
    }
  });
}

e.g. with promise

function example(input) {
  doSomethingAsync1(input).then(res1 => {
    return doSomethingAsync2(res1);
  }).then(res2 => {
    return doSomethingAsync3(res2);
  }).then(res3 => {
    console.log(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);
  console.log(res3);
}

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 9 months ago loading comments...