2

I'm a newcomer to

I am confused about using promise rather than callback.

When do I need while exists?

What are the properties of callback that force me to use it, not promise?

PeterMader
  • 6,987
  • 1
  • 21
  • 31
mo30
  • 89
  • 1
  • 6
  • both are used to handle asynchronous programming. as far as i know, one advantage of using promises is avoiding callback hell. refer https://javascript.info/promise-chaining – Pranay Kumar Aug 12 '17 at 16:58
  • 1
    Promises cannot exist without "callbacks" - their constructor and their `then` method take ones. – Bergi Aug 12 '17 at 17:05
  • @Bergi ... well, when coupled with async/await that is all hidden from you. – Meirion Hughes Aug 12 '17 at 17:07
  • There are thousands of articles about promises and just as many coding examples both on the general web and here. It would likely be more useful to all if you read a bunch of those articles and then asked a much more specific question about exactly what you didn't understand in one of those articles. You are essentially asking "what are promises and what are they good for" which is like too broad for stack overflow. Answering your question well requires a multi-page tutorial that attempts to teach the concept of promises without an actual specific coding problem to solve. – jfriend00 Aug 12 '17 at 17:16
  • 1
    Promises are a tool for managing asynchronously retrieved results. If you have a single async operation, there is little complexity difference between using a plain callback API vs. using a promise API. But, as soon as you have more than one async operation that you need to sequence, coordinate, run in parallel, etc... the complexity of code to write where you properly order the operations, collect all the results and propagate all the errors is vastly simpler with promises than with ordinary callbacks. – jfriend00 Aug 12 '17 at 17:20
  • Then, once you learned how to use promises for the more complicated stuff, you will find you want to use them for all async programming because they're just more streamlined to write and debug and use. Then, when you combine them with `async` and `await` in ES7 (which only work with promises), you can simplify your coding even more. – jfriend00 Aug 12 '17 at 17:20
  • 1
    Possible duplicate: [Asynchronous JavaScript - Callbacks vs Deferred/Promise](https://stackoverflow.com/questions/14127703/asynchronous-javascript-callbacks-vs-deferred-promise). Related answers: [Node.js - best practice error handling](https://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling/36703397#36703397) and [Why are callbacks more tightly coupled than promises](https://stackoverflow.com/questions/21141817/why-are-callbacks-more-tightly-coupled-than-promises). – jfriend00 Aug 12 '17 at 17:25
  • 1
    Other related answers: [What is the difference between callback and promise](https://stackoverflow.com/questions/14244775/what-is-the-difference-between-callback-and-promise) and [Aren't promises just callbacks](https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks) and [What are the differences between Deferred, Promise and Future in Javascript](https://stackoverflow.com/questions/6801283/what-are-the-differences-between-deferred-promise-and-future-in-javascript). I think the ground is pretty much covers in those 6 other questions/answers. – jfriend00 Aug 12 '17 at 17:31
  • 1
    Promises are to callbacks as words are to letters or monads are to arrows: they are a more powerful but less generic abstraction. Callbacks can be used for much more, but when you can use promises they're usually the better choice. – Bergi Aug 12 '17 at 17:51

1 Answers1

1

MDN has a pretty good definition of promises:

A promise represents the eventual completion (or failure) of [one] asynchronous operation, and its resulting value.

Promises are not about reoccurring events, which are often handled by functions that you pass as callbacks.

In many cases, callback APIs can be refactored to work with promises:

request('file.txt', function (err, result) {
  if (err) {
    console.error('An error occurred:', err);
  }
  console.log(result);
});

Using promises, this can be rewritten to:

request('file.txt')
  .then(result => console.log(result))
  .catch(err => console.log('An error occurred:', err));

However, a promise can resolve only once. The request function in the snippet above can be wrapped in a promise API because the callback will only be executed once. But if you handle multiple events with a single callback function, it gets hard to rewrite the code to use promises:

server.on('request', function (req, res) {
  // ...
});

How would you rewrite that?

Observables would be one way to deal with this. They allow you to react to multiple asynchronous actions. If you start to do some research about observables, you will get to see this table:

|          | Singular       | Plural            |
|----------|----------------|-------------------|
| Spatial  | Value          | Iterable<Value>   |
| Temporal | Promise<Value> | Observable<Value> |
PeterMader
  • 6,987
  • 1
  • 21
  • 31