Reputation: 89
I'm a newcomer to node.js
I am confused about using promise rather than callback.
When do I need callback while promise exists?
What are the properties of callback that force me to use it, not promise?
Upvotes: 2
Views: 1875
Reputation: 7285
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> |
Upvotes: 1