Node.js: When to Use Promises vs Callbacks

I have an old Node.js code that I am updating. In this process, I develop new modules for working with old code. I find this now, unlike when I first wrote this, I rely more on using ES6 promises rather than callbacks. So now I have this combination of some functions that return promises, and some callbacks are tedious. I think that ultimately it should be reorganized to use promises. But before that is done ...

What are situations where promises are preferred and where are callbacks preferred?

Is there any situation that a callback can handle better than a promise and vice versa?

Based on what I have seen so far, I see no reason to use callbacks instead of promises. It's true?

+15
source share
3 answers

First, you almost never want to write code that is a mixture of callbacks and promises for asynchronous operations. If you move on to promises or enter some promises, then you might want to reorganize callbacks in the same section of code into promises. For the corresponding types of operations, there are so many advantages of promises over simple callbacks that it is worth the effort to convert when you are already working in the field of code.

Promises are great for:

  • Monitoring synchronous operations
  • ( )
  • , ,
  • , async/await ( )
  • , Promise, : pending, fulfilled rejected pending => fulfilled pending => rejected ( ).
  • (, , , , )
  • , ( ).

, :

  • ( Array.prototype.map())
  • , (, , ). .
  • , , , .

EventEmitter .

EventEmitters :

  • /
  • , (, )
  • , - API, eventEmitter. API . eventEmitter , .

Promises

, callback(err, result), util.promisify() util.promisify() node.js Bluebird, Promise.promisify().

Bluebird ( node.js), :

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));

fs.writeFileAsync("file.txt", data).then(() => {
    // done here
}).catch(err => {
    // error here
});

node.js 8+

util.promisify() , node.js, , .

:

const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);

// usage of promisified function
stat('.').then((stats) => {
  // Do something with 'stats'
}).catch((error) => {
  // Handle the error.
});
+31

, .

, , , , . , , , Error, . , , . , , , .

, , , , , util.promisify() util.promisify(), Node.js, Call-First Callbacks . async/await Node.js, Promises.

, , , Promises async/await . - , .

+6

, , .

. . , , , . , , , , : 1. 2. . 3.

1. . Promises javascript. , . - . -

aAsync()   
.then(bAsync)  
 .then(cAsync)   
.done(finish); 

, ,

aAsync(function(){
    return bAsync(function(){
        return cAsync(function(){
            finish()         
        })     
    }) 
}); 

2. . , , . . : ? , , :

api()
.then(function(result) {   
    return api2(); 
})
.then(function(result2){     
    return api3(); 
})
.then(function(result3){      
    // do work 
})
.catch(function(error) {    
    //handle any error that may occur before this point 
}); 
/* Pretty much the same as a try { ... } catch block. 
Even better: */
api()
.then(function(result){
    return api2(); })
.then(function(result2){
    return api3(); })
.then(function(result3){
    // do work 
})
.catch(function(error) {
    //handle any error that may occur before this point 
})
.then(function() {
    //do something whether there was an error or not      
    //like hiding an spinner if you were performing an AJAX request. 
});

3. : , 3 api, api2, api3 (, AJAX), ? - . , ES6, :

Promise.all([api(), api2(), api3()])
.then(function(result) {
    //do work. result is an array containing the values of the three fulfilled promises. 
})
.catch(function(error) {
    //handle the error. At least one of the promises rejected. 
});

, .

+1
source

Source: https://habr.com/ru/post/1681210/


All Articles