2016-04-06 15 views

risposta

14

Bookshelf utilizza Bluebird per le loro promesse, e credo .tap() è una delle loro specifiche Promise metodi. Sembra che ti permetta di chiamare essenzialmente un .then() senza alterare il valore che passa attraverso la catena.

http://bluebirdjs.com/docs/api/tap.html

modifica: causa di una richiesta di ulteriori chiarimenti, ecco un esempio della differenza tra Promise#tap() e Promise#then(). Si noti che Promise#tap() è non standard ed è specifico per Bluebird.

var Promise = require('bluebird'); 

function getUser() { 
    return new Promise(function(resolve, reject) { 
    var user = { 
     _id: 12345, 
     username: 'test', 
     email: '[email protected]' 
    }; 
    resolve(user); 
    }); 
} 

getUser() 
    .then(function(user) { 
    // do something with `user` 
    console.log('user in then #1:', user); 
    // make sure we return `it`, 
    // so it becomes available to the next promise method 
    return user; 
    }) 
    .tap(function(user) { 
    console.log('user in tap:', user); 
    // note that we are NOT returning `user` here, 
    // because we don't need to with `#tap()` 
    }) 
    .then(function(user) { 
    // and that `user` is still available here, 
    // thanks to using `#tap()` 
    console.log('user in then #2:', user); 
    }) 
    .then(function(user) { 
    // note that `user` here will be `undefined`, 
    // because we didn't return it from the previous `#then()` 
    console.log('user in then #3:', user); 
    }); 
+0

Potresti elaborare? Non capisco quale valore sarebbe stato modificato da allora(). Sono davvero nuovo alla libreria/promesse – 1mike12

+1

Sure. L'essenza di ciò è che non devi restituire un valore quando usi 'tap()', ma lo fai quando usi 'then()' (assumendo che tu voglia che il valore scorra attraverso la catena delle promesse). Vedi la mia risposta aggiornata per un esempio più completo. – dvlsg

+1

Ora finalmente lo capisco! Grazie mille per l'ulteriore riscrittura – 1mike12

1

Secondo Reg “raganwald” Braithwaite,

rubinetto è un nome tradizionale mutuato da vari comandi shell Unix. Prende un valore e restituisce una funzione che restituisce sempre il valore, ma se si passa una funzione, esegue la funzione per gli effetti collaterali . [source]

Here è la stessa domanda posta per underscore.js.

L'essenza è questa: tutto tocca fa è restituire l'oggetto che è stato passato. Comunque, se viene passata una funzione, eseguirà quella funzione. Quindi, è utile per il debug o per l'esecuzione di effetti collaterali all'interno di una catena esistente senza alterare quella catena.