Future Completer.future - dart

Could someone please explain to me what is wrong with the following code.
The line .then((result) {window.alert("Record = ${oDbRec}");}) displays the following :
Record = Instance of '_ThenFuture#0x2900bd4a'
What I want is the result from the getObject(). The code:
fHtmDisplayOneClient(String sKey) {
var oDbRec;
oDbRec = fDbSelectOneClient(sKey)
.then((result) {window.alert("Record = ${oDbRec}");})
..catchError((oError) {window.alert("Error from fDbSelectOneClient. ${oError}");
});
}
Future fDbSelectOneClient(String sKey) {
var completer = new Completer();
idb.Transaction oDbTxn = ogDb1.transaction(sgTblClient, 'readwrite');
idb.ObjectStore oDbTable = oDbTxn.objectStore(sgTblClient);
idb.Request oDbReqGet = oDbTable.getObject(sKey);
oDbReqGet.onSuccess.first.then((val) => completer.complete(oDbReqGet.result));
oDbReqGet.onError.first.then((err) => completer.completeError(err));
return completer.future; // return the future
}

I think you want what the future returns, which is the 'result' object passed to .then()
.then((result) => print('$result'));

Related

Return value from subscribe in Ionic

So I want to return a value from a subscribe function like this:
async obtenerListadoClases(categoria) {
var clasesDB = await this.getClases(categoria)
.subscribe((data: any) => {
clasesDB = data.clasesDB // **Want to return this**
console.log(clasesDB,'clasesDB'); // **Getting Value**
})
console.log(clasesDB, 'outside'); // **Not Getting Value**
return clasesDB;
}
Also, I want to use this function in another place like this:
var listaClases = await this.claseServicio.obtenerListadoClases(categoria); // Not getting the correct info
// console.log(listaClases , 'listado clases');
What Im doing wrong? Or how can I fix it? Thanks in advance!
You can only subscribe to observables.
The Observable way
getClases(categoria): Observable<any> {
return new Observable(observer => {
// logic to return data
observer.next(data);
observer.complete()
// logic when error
observer.error(error);
});
}
Return the getClases() function
obtenerListadoClases(categoria): Observable<any>{
return this.getClases(categoria);
}
Use the function where you want:
this.obtenerListadoClases(categoria)
.subscribe(
result => {
// what you want to do with the result
},
error => {
// what you want to do with the error
});
The Promise way
getClases(categoria): Promise<any> {
return new Promise((resolve, reject) => {
// logic to return data
resolve(data);
// logic when error
reject(error);
});
}
Return the getClases() function
obtenerListadoClases(categoria): Promise<any>{
return this.getClases(categoria);
}
Use the function where you want:
this.obtenerListadoClases(categoria)
.then(result => {
// what you want to do with the result
})
.catch(error => {
// what you want to do with the error
});
You should be using promises with the .subscribe(). Only observables use .subcribe()
Also, stay away from promises in the angular world. Time to think reactive.
Is this returning an observable? this.getClases(categoria) post the code please.

Chaining Futures Do Not Execute In Order

I'm currently reading variables from a Bluetooth device. This obviously takes an undetermined amount of time, so I am using futures (This method is readCharacteristic in my code down below).
More than one read operation cannot take place at a time - if a second read operation is started while a first operation is still in progress, Flutter will throw an error.
My understanding was that chaining futures together using .then() would only allow the next statement to execute when the previous call had finished. This idea seems to be true until I try to read a third value - that is when the error is thrown, because of the overlapping read events.
Here is my code:
readCharacteristic(scanDurationCharacteristic)
.then((list) => sensorScanDuration = list[0].toDouble())
.then((_) {
readCharacteristic(scanPeriodCharacteristic)
.then((list) => sensorScanPeriod = list[0].toDouble());
}).then((_) {
readCharacteristic(aggregateCharacteristic)
.then((list) => sensorAggregateCount = list[0].toDouble());
}).then((_) {
readCharacteristic(appEUICharacteristic)
.then((list) => appEUI = decimalToHexString(list));
}).then((_) {
readCharacteristic(devEUICharacteristic)
.then((list) => devEUI = decimalToHexString(list));
}).then((_) {
readCharacteristic(appKeyCharacteristic)
.then((list) => appKey = decimalToHexString(list));
});
What is a better way to ensure that these read events will not overlap?
Although R.C Howell answer is correct, prefer using async/await keywords instead. This is much more readable and you're less likely to make an error
Future<void> scanBluetooth() async {
sensorScanDuration = (await readCharacteristic(scanDurationCharacteristic))[0].toDouble();
sensorScanPeriod = (await readCharacteristic(scanPeriodCharacteristic))[0].toDouble();
sensorAggregateCount = (await readCharacteristic(aggregateCharacteristic))[0].toDouble();
appEUI = await readCharacteristic(appEUICharacteristic).then(decimalToHexString);
devEUI = await readCharacteristic(devEUICharacteristic).then(decimalToHexString);
appKey = await readCharacteristic(appKeyCharacteristic).then(decimalToHexString);
}
If you would like to chain Futures, you must return the previous Future from within the then method of the previous Future.
The documentation says to chain like so,
expensiveA()
.then((aValue) => expensiveB())
.then((bValue) => expensiveC())
.then((cValue) => doSomethingWith(cValue));
Which is the same as,
expensiveA()
.then((aValue) {
return expensiveB();
}).then((bValue) {
return expensiveC();
}).then((cValue) => doSomethingWith(cValue));
As this applies to your case,
readCharacteristic(scanDurationCharacteristic)
.then((list) {
sensorScanDuration = list[0].toDouble();
return readCharacteristic(scanPeriodCharacteristic);
}).then((list) {
sensorScanPeriod = list[0].toDouble());
return readCharacteristic(aggregateCharacteristic);
}).then((list) {
sensorAggregateCount = list[0].toDouble());
return readCharacteristic(appEUICharacteristic);
}).then((list) {
appEUI = decimalToHexString(list));
return readCharacteristic(devEUICharacteristic);
}).then((list) {
devEUI = decimalToHexString(list));
return readCharacteristic(appKeyCharacteristic);
}).then((list) => appKey = decimalToHexString(list));

Bad state: Stream has already been listened to Flutter error

I am calling an api. I am getting a streamed response after sending the request. But i cannot parse the response and convert it to String/JSON. This is where I am calling the api.
static Future<String> callDeviceListFetchApi() async {
Completer completer = new Completer();
String jsonResponse;
String url = Constants.BASE_URL + Constants.DEVICE_REGISTER_URL;
var client = new http.Client();
var request = new http.Request('GET', Uri.parse(url));
request.headers[HttpHeaders.CONTENT_TYPE] = 'application/json';
request.headers[HttpHeaders.AUTHORIZATION] = '<auth code>';
await client.send(request).then((response) {
response.stream.bytesToString().then((value) {
print(value.toString());
jsonResponse = value.toString();
completer.complete(jsonResponse);
});
}).catchError((error) {
print(error.toString());
});
return completer.future;
}
I am getting the error,
Bad state: Stream has already been listened to Flutter error. Any idea why this is happening?
There's a couple of things wrong with your code. I think you have a slight misunderstanding about how Async and Futures work in dart - you should re-read the docs and this tutorial (part 1 and part 2).
Basically, the problem is that you were returning a 'Future' from an async function. If you return a future from an async function, it has issues (I don't know why the analyzer doesn't catch that).
Future<String> callDeviceListFetchApi() async {
Completer completer = new Completer();
String url = "<url>";
var client = new http.Client();
var request = new http.Request('GET', Uri.parse(url));
request.headers[HttpHeaders.CONTENT_TYPE] = 'application/json';
request.headers[HttpHeaders.AUTHORIZATION] =
'<auth string>';
var response = await client.send(request);
String jsonResponse;
try {
var value = await response.stream.bytesToString();
print(value.toString());
jsonResponse = value.toString();
} catch (error) {
print(error.toString());
}
return completer.complete(jsonResponse);
}
Or not async:
Future<String> callDeviceListFetchApiNotAsync() {
String url = "<url>";
var client = new http.Client();
var request = new http.Request('GET', Uri.parse(url));
request.headers[HttpHeaders.CONTENT_TYPE] = 'application/json';
request.headers[HttpHeaders.AUTHORIZATION] =
'<auth string>';
Completer completer = new Completer();
return client.send(request).then((response) {
return response.stream.bytesToString();
}).then((value) {
print(value.toString());
return value.toString();
}).catchError((error) {
print(error.toString());
// if you use catchError, whatever you return from it
// is the value you'll get wherever you resolve the future.
return null;
});
}
But unless you're trying to do something I'm not seeing, there's a way easier way to do this (assuming all you want to do is get a string from a server):
Future<String> getList() async {
var response = await http.get("<url>", headers: {
HttpHeaders.CONTENT_TYPE: 'application/json',
HttpHeaders.AUTHORIZATION: '<auth string>',
});
if (response.statusCode == 200) {
return response.body;
} else {
throw Error();
}
}

Where should I put completer.complete() in this series of Future functions?

My function have to create a directory, and copy the entire folder hierarchy from another directory to this new one. All of the operation are done asynchronously, but I want this function to return a Future that when I call the .then(result) on it, will have done all of the asynchronously work.
But I don't know where exactly I should put my completer.complete() to achieve that.
Future<Directory> createCopyDirectory(Directory directoryToCreate){
Completer<Directory> completer = new Completer<Directory>();
completer.complete(
directoryToCreate.create().then((directory){
Directory contentToCopy = new Directory(globalPathOfDirectoryToCopy);
List<Future> creatingContent = new List<Future>();
contentToCopy.list(recursive:true, followLinks:false).forEach((f){
if (f is File){
File fileToCreate = new File(f.path.replaceFirst('pages', userID));
creatingContent.add(fileToCreate.create(recursive:true).then((_){
f.readAsString().then((fileContent){
fileToCreate.writeAsString(fileContent);
});
}));
}
});
return Future.wait(creatingContent).then((_){ return directoryToCreate;});
})
);
return completer.future;
}
I precise that my function work like expected, But if I try to access directly the content I should have created in this function, like in the then() call, Dart bring me an expection like I have not created the content. So the completer.complete() is surely badly placed and call then() before the content has been created.
I have tried with the completer.complete() on the ending Future.wait(creatingContent) or by replacing return directoryToCreate by completer.complete(directoryToCreate) but the result is the same.
I am a bit confused on the way to build a proper Future based function in this kind of situation.
You shouldn't need a Completer here.
Future<Directory> createCopyDirectory(Directory directoryToCreate) {
return directoryToCreate.create().then((directory) {
String userID = split(userDirectory.path).last;
Directory contentToCopy = new Directory(globalPathOfDirectoryToCopy);
List<Future> creatingContent = new List<Future>();
return contentToCopy
.list(recursive: true, followLinks: false)
.forEach((File f) {
if (f is File) {
File fileToCreate = new File(f.path.replaceFirst('pages', userID));
creatingContent.add(fileToCreate.create(recursive: true).then((_) {
return f.readAsString().then((fileContent) {
return fileToCreate.writeAsString(fileContent);
});
}));
}
}).then((_) {
return Future.wait(creatingContent).then((_) {
return directoryToCreate;
});
});
});
}
Just to demonstrate how you could use the Completer:
Future<Directory> createCopyDirectory(Directory directoryToCreate) {
Completer<Directory> completer = new Completer<Directory>();
directoryToCreate.create().then((directory) {
String userID = split(userDirectory.path).last;
Directory contentToCopy = new Directory(globalPathOfDirectoryToCopy);
List<Future> creatingContent = new List<Future>();
contentToCopy.list(recursive: true, followLinks: false).forEach((f) {
if (f is File) {
File fileToCreate = new File(f.path.replaceFirst('pages', userID));
creatingContent.add(fileToCreate.create(recursive: true).then((_) {
return f.readAsString().then((fileContent) {
return fileToCreate.writeAsString(fileContent);
});
}));
}
}).then((_) => Future
.wait(creatingContent)
.then((_) => completer.complete(directoryToCreate)));
});
return completer.future;
}

sqljocky query does not have a method 'then' (dart database access)

I'm trying to code sql access to a database using sqljocky in Dart. As I want to make some computation with the result returned by my database Handler, the method return a Future.
But when I try to run it, I'm getting the following error:
Uncaught Error: The null object does not have a method 'then'`
I've ran the debugger and found that this error raise on:
db.query('select * from user where email="$email"').then(...)
but the catchError clause doesn't fire.
My handler method is:
// db is a ConnectionPool
Future<Map<String,String>> queryUser(String email){
print(email);
db.query('select * from user where email="${email}"').then((result) { // here raise the error
Map<String,String> results = new Map<String,String>();
result.forEach((row){
results['status'] = '200';
results['ID'] = row[0];
results['Image'] = row[1];
results['Name'] = row[2];
results['Email'] = row[3];
results['Password'] = row[4];
});
return results;
}).catchError((error){
Map<String,String> results = new Map<String,String>();
results['status'] = '500';
return results;
});
}
And the method that call this handler is:
List getUser(String email) {
Future<Map<String,String>> result = dbhandler.queryUser(email);
result.then((Map<String,String> result) {
String statuscode = result['status'];
result.remove('status');
String json = JSON.encode(result);
List pair = new List();
pair.add(statuscode);
pair.add(json);
return pair;
});
If I run the query directly in phpmyadmin, it return correct data, so it is correct.
Can someone give me a hint about how to solve it?
The queryUser() method will always return null, as there is no return statement. In the next release of Dart there will be a static hint warning for this, but at the moment there is none.
Perhaps the code below is what you meant to do. Note the initial return statement before db.query(), and the extra result.toList() call. I haven't tested this, so there's probably a typo or two.
Future<Map<String,String>> queryUser(String email){
print(email);
return db.query('select * from user where email="${email}"')
.then((result) => result.toList())
.then((rows) {
var row = rows.single;
Map<String,String> results = new Map<String,String>();
results['status'] = '200';
results['ID'] = row[0];
results['Image'] = row[1];
results['Name'] = row[2];
results['Email'] = row[3];
results['Password'] = row[4];
return results;
}).catchError((error){
Map<String,String> results = new Map<String,String>();
results['status'] = '500';
return results;
});
}
You can also make this a bit cuter using map literals:
Future<Map<String,String>> queryUser(String email){
return db.query('select * from user where email="${email}"')
.then((result) => result.toList())
.then((rows) => <String, String> {
'status': '200',
'ID': rows.single[0],
'Image': rows.single[1],
'Name': rows.single[2],
'Email': rows.single[3],
'Password': rows.single[4] })
.catchError((error) => <String, String> {'status': '500'});
}
Finally I found the answer using Completer to control the Future object, but the real problem was, as Greg Lowe said, that my methods doesn't return anything as they come to end before the then clause.
Using completer, I've made my query method as:
Future<Map<String,String>> queryUser(String email){
Completer c = new Completer();
db.query('select * from user where email="$email"').then((result) {
Map<String,String> results = new Map<String,String>();
result.forEach((row){
results['status'] = '200';
results['ID'] = row[0].toString();
results['Image'] = row[1];
results['Name'] = row[2];
results['Email'] = row[3];
results['Password'] = row[4];
}).then((onValue){
c.complete(results);
});
}).catchError((error){
Map<String,String> results = new Map<String,String>();
results['status'] = '500';
c.completeError((e) => print("error en queryUser"));
});
return c.future;
}
I also solved an error when using the foreach method, at first I supposed it return nothing, but after that, I noticed that it return a Future, so I added a then clause.
And my getUser method:
Future<List> getUser(String email) {
Completer c = new Completer();
Future<Map<String,String>> result = dbhandler.queryUser(email);
result.then((Map<String,String> result) {
String statuscode = result['status'];
result.remove('status');
String json = JSON.encode(result);
List pair = new List();
pair.add(statuscode);
pair.add(json);
c.complete(pair);
});
return c.future;
}
After those changes, everything works right

Resources