dart
Programmazione asincrona
Ricerca…
Restituire un futuro usando un Completatore
Future<Results> costlyQuery() {
var completer = new Completer();
database.query("SELECT * FROM giant_table", (results) {
// when complete
completer.complete(results);
}, (error) {
completer.completeException(error);
});
// this returns essentially immediately,
// before query is finished
return completer.future;
}
Async e attendere
import 'dart:async';
Future main() async {
var value = await _waitForValue();
print("Here is the value: $value");
//since _waitForValue() returns immediately if you un it without await you won't get the result
var errorValue = "not finished yet";
_waitForValue();
print("Here is the error value: $value");// not finished yet
}
Future<int> _waitForValue() => new Future((){
var n = 100000000;
// Do some long process
for (var i = 1; i <= n; i++) {
// Print out progress:
if ([n / 2, n / 4, n / 10, n / 20].contains(i)) {
print("Not done yet...");
}
// Return value when done.
if (i == n) {
print("Done.");
return i;
}
}
});
Vedi esempio su Dartpad: https://dartpad.dartlang.org/11d189b51e0f2680793ab3e16e53613c
Conversione di callback in Futures
Dart ha una robusta libreria asincrona, con Future , Stream e altro. Tuttavia, a volte potresti imbatterti in un'API asincrona che utilizza callback anziché Futures . Per colmare il divario tra callback e Futures, Dart offre la classe Completer . È possibile utilizzare un Completamento per convertire una richiamata in un futuro.
I completatori sono ottimi per il collegamento di un'API basata sul callback con un'API basata sul futuro. Ad esempio, supponiamo che il tuo driver di database non usi Futures, ma devi restituire un futuro. Prova questo codice:
// A good use of a Completer.
Future doStuff() {
Completer completer = new Completer();
runDatabaseQuery(sql, (results) {
completer.complete(results);
});
return completer.future;
}
Se si utilizza un'API che restituisce già un Futuro, non è necessario utilizzare un Completamento.
Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow