-1

Can we achieve the same goal from callbacks & promises, if so then why use one over the other?

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77
ram1993
  • 979
  • 1
  • 9
  • 13

2 Answers2

1

Besides the reasons you mentioned, you can store the promise and use it elsewhere in your code. Promises also follow a more object oriented paradigm.

code11
  • 1,986
  • 5
  • 29
  • 37
1

(Not opinion-based:)

Propagating errors correctly back to a call-site with plain callbacks is near-impossible in a long chain of asynchronous operations, without reinventing something like promises.

If you throw in a regular callback, where does the error go? Compare:

setTimeout(() => { throw new Error("Fail"); }, 1000);

vs.

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

wait(1000)
 .then(() => { throw new Error("Fail"); })
 .catch(e => console.log("Caught: " + e)); // Caught: Error: Fail

In the former case it goes straight to the browser's console without the JS knowing, whereas in the latter case it's caught by the JS, which can take corrective action.

Propagating errors correctly in general without promises would require try {} catch() {} with propagation magic around every callback in the code, something I've never seen.

jib
  • 40,579
  • 17
  • 100
  • 158
  • Your examples are not comparable. The first example should be: ```var wait = setTimeout; wait(1000, function() { try { throw new Error("Fail"); } catch (e) { console.log("Caught: " + e); } })```. As you can see, this example is significantly more straightforward and more understandable than the example with a promise. – Mihail H. May 28 '21 at 11:04
  • @MihailH. Sure, but you haven't propagated the error anywhere. [The point of promises is to give us back functional composition and error bubbling in the async world](https://gist.github.com/domenic/3889970#what-is-the-point-of-promises). For readability, use `async`/`await`. – jib May 28 '21 at 20:08