2013-05-08 7 views
14

ho qualche codice come:Binding una funzione di gestione promessa di un oggetto

var bar = foo().then(function success(value) { 
    // compute something from a value... 
}, function failure(reason) { 
    // handle an error... 
}); 

Come faccio lego la funzione failure all'oggetto this nel contesto di bar. So che dovrò usare myFunc.bind(this) ma cosa devo sostituire al posto di myFunc?

+0

Che tipo di promisses stai parlando? JavaScript è ancora in discussione per ES6 – fmsf

+0

Sì, sto parlando di promesse JavaScript. –

+0

È difficile da credere, le promesse di j6 di es6 non sono ancora state implementate. È necessario fornire più contesto. http://mozilla.6506.n7.nabble.com/Promise-Future-asynchrony-in-then-td278846.html#a279080 – fmsf

risposta

35

È possibile utilizzare bind come questo:

var bar = foo().then(function success(value) { 
    // compute something from a value... 
}, function failure(reason) { 
    // handle an error... 
}.bind(this)); 
4

Al momento è una funzione anonima (anche se l'etichetta) per la richiamata fallimento:

function failure(reason) { 
    // handle an error... 
} 

Come robertklep dice, si può immediatamente chiamare .bind su quella funzione anonima. Tuttavia, potrebbe essere più leggibile di utilizzare una funzione denominata invece, e passarlo in .then() come una variabile:

function success(value) { 
    // compute something from a value... 
} 
function failure(reason) { 
    // handle an error... 
} 
var bar = foo().then(success, failure.bind(this)); 
+0

Penso che tu intenda "fallimento = failure.bind (questo) '? – robertklep

+1

@robertklep Ah, potrebbe essere; Non ho molta familiarità con '.bind()'. Se restituisce un nuovo oggetto, piuttosto che agire sul posto, suppongo che 'foo(). Then (success, failure.bind (this));' sia abbastanza leggibile. – IMSoP

+1

sì restituisce un nuovo oggetto :) per essere più leggibile, è una questione di dibattito;) – robertklep

0

Quello che ho trovato molto utile è quello di legare ogni gestore then() 's [funzione] per il vuoto oggetto, quindi ogni funzione potrebbe avere accesso ad essa. Quindi l'utente può impostare e ottenere le proprietà in ciascuna promessa tramite la parola chiave this. I quadri di test unitario funzionano in modo simile.

chainPromiseList([getName,getAge],finalDone,rejectHandle); 
 

 
    function chainPromiseList(promiseList,finalDone,errHandle){ 
 
     var userContext = new UserContext(); 
 
     if(typeof finalDone==='function') promiseList.push(finalDone); 
 
     if(typeof errHandle==='function') promiseList.push(errHandle); 
 
     return promiseList.reduce((total,curVal,curInd,arr)=>{ 
 
     var last = curInd+1===arr.length; 
 
     var method = last&&typeof errHandle==='function' ? 'catch':'then'; 
 
     var concatenated = total[method](curVal.bind(userContext)); 
 
     return concatenated; 
 
     },Promise.resolve()); 
 
     function UserContext(){}; 
 
    } 
 
    
 
    function getName(){ 
 
     return new Promise((resolve,reject)=>{ 
 
     setTimeout(()=>{ 
 
      console.log('got name!'); 
 
      this.name = 'Paul'; 
 
      resolve(); 
 
     },500); 
 
     }); 
 
    } 
 

 
    function getAge(){ 
 
     return new Promise((resolve,reject)=>{ 
 
     setTimeout(()=>{ 
 
      console.log('got age!'); 
 
      this.age = 26; 
 
      resolve(); 
 
     },500); 
 
     }); 
 
    } 
 

 
    function finalDone(){ 
 
     console.log(`Hello, I'm ${this.name} and I'm ${this.age}yo.`); 
 
    } 
 

 
    function rejectHandle(msg){ 
 
     console.log('Error: ',msg); 
 
    }

Problemi correlati