2015-11-23 12 views
15

È o sarà possibile avere un getter classe ES6 restituire un valore da una funzione attesa/asincrona ES2017.(ES6) class as2/aspit getter

class Foo { 
    async get bar() { 
     var result = await someAsyncOperation(); 

     return result; 
    } 
} 

function someAsyncOperation() { 
    return new Promise(function(resolve) { 
     setTimeout(function() { 
      resolve('baz'); 
     }, 1000); 
    }); 
} 

var foo = new Foo(); 

foo.bar.should.equal('baz'); 
+3

Questo è tutto ciò che serve: 'ottenere bar() {return someAsyncOperation(); } ' –

+0

@FelixKling Ho aggiornato il mio post per spero di chiarire la mia domanda. Non sto cercando di restituire una funzione dal getter. Voglio che il valore restituito provenga da un'operazione asincrona. – Enki

+0

Sì, 'return someAsyncOperation();' restituisce la promessa che 'someAsyncOperation' restituisce. Non restituisce una funzione (cosa ti ha fatto pensare che?) –

risposta

11

È possibile solo await promesse, e async funzioni tornerà promesse stesse.
Ovviamente un getter può dare una tale promessa altrettanto bene, non c'è differenza da un valore normale.

13

È possibile farlo

class Foo { 
    get bar() { 
     return (async() => { 
      return await someAsyncOperation(); 
     })(); 
    } 
} 

che è ancora una volta la stessa

class Foo { 
    get bar() { 
     return new Promise((resolve, reject) => { 
      someAsyncOperation().then(result => { 
       resolve(result); 
      }); 
     }) 
    } 
}