Using Futures with Dart - dart

Why is the print result keep returning "asd"?
var jerl = "asd";
HttpRequest.request('Foo',
method: "GET",
requestHeaders: {"Authorization": "Secret"}).then((x) => x.responseText).then((y) => jerl = y);
print(jerl);

Async code is just scheduled for later execution and the sync code continues executing without waiting for the async code. The method you pass to Future.then(...) is executed when the scheduled async code is finished. You find a lot of such questions and examples tagged [:dart-async:] here on StackOverflow.
If you want code to be executed when the async code completed you need to chain it with then like you did with other code
var jerl = "asd";
HttpRequest.request('Foo',
method: "GET",
/* return */ requestHeaders: {"Authorization": "Secret"})
.then((response) {
var jer1 = x.responseText;
print(jerl);
});
You can use the async/await feature to make code look more like sync code
Future someMethod() async { // <== added `Future` and `async`
var jerl = "asd";
var response = await HttpRequest.request('Foo', // <== added `await`
method: "GET",
requestHeaders: {"Authorization": "Secret"}).then((x) =>
print(response.text);
}
async is contagious. There is no way to go back from async execution to sync execution. If your code calls any async method or function and you need code further down to wait for the async result, then you need to chain all following code (also in calling methods) with .then (or use async/await). For this to work you also need to return the future to the caller so he can call .then() on it.
With async/await you don't need to explicitly return the future.
async/await doesn't make async code sync (as mentioned above), it only makes it look more like sync code. The underlying behavior is identical as with then.

Related

How to rewrite code with then to await version

I wrote code
pendingFutures.addAll({sqlQuery.hashCode: connection.query(sqlQuery, timeoutInSeconds: 3600)});
var queryResult = await pendingFutures[sqlQuery.hashCode];
var queryObj = RequestCacheStruct(sqlQuery.hashCode, DateTime.now(), queryResult! );
await pendingFutures.remove(sqlQuery.hashCode);
requestsCacheList.add(queryObj);
But it's seems that code above have different behavior than code below:
pendingFutures[sqlQuery.hashCode] =
connection.query(...)
.then((queryResult) {
// TODO: add queryResult into cache.
});
await pendingFutures[sqlQuery.hashCode];
How to fix first code to make it work as second one?
My friend who wrote second code said:
"In the first case, await pendingFutures[...] will return as soon as the request is finished.
In the second - when the request is finished and the record is added to the cache."
I'll try to distill your examples down so that they're proper apples-to-apples comparisons. Given:
theFuture = someAsyncOperation();
var result = await theFuture;
addToCache(result);
additionalWork();
and
theFuture = someAsyncOperation().then((result) => addToCache(result));
await theFuture;
additionalWork();
where theFuture is some non-local variable, then those await theFuture; lines should not result in any material difference: addToCache will be called before additionalWork.
However, a more interesting question (and probably what your friend meant) is that if theFuture is separately awaited:
await theFuture;
yetMoreWork();
will it be guaranteed that yetMoreWork is called after addToCache? In other words: if two .then() callbacks are registered on the same Future, are the callbacks guaranteed to be fired in order of registration? (From what I've observed, it seems that way, but I don't know if it's necessarily true, or even if it is, if it will be guaranteed to be true in the future.)
Back to your original question: how can you rewrite the first form to use only await but still guarantee that operations are serialized in a well-defined manner? You have to create a Future that completes after addToCache is called, and you can do that with a helper function:
Future<void> helperFunction() async {
var result = await someAsyncOperation();
addToCache(result);
}
theFuture = await helperFunction();
additionalWork();

dart - correct coding pattern for subscription when using null saftey?

I've enabled the dart 2.8 experimental null saftey.
I have the following exiting code.
StreamSubscription<String> subscription;
subscription =
response.transform(Utf8Decoder()).transform(LineSplitter()).listen(
(line) async {
result += line;
},
onDone: () async {
unawaited(subscription.cancel());
completer.complete(result);
},
);
With null saftey enabled I get a error in the 'onDone' method where it calls subscription.cancl
"The expression is nullable and must be null-checked before it can be used.
Try checking that the value isn't null before using it.",
I can fix the problem by putting a conditional before the call to cancel, but this seems unnecessary as in reality subscription can never be null.
Is there a coding pattern that allows subscription to be declared as non-null?
The problem here is that the read of subscription happens at a place where it's still potentially unassigned. It isn't, actually, but we only know that because the listen method promises not to call any of the callbacks before returning. The compiler can't see that. So, you need to move the reading to after the assignment.
What I'd do to make this listen call work:
var buffer = StringBuffer(result);
var subscription = response
.transform(Utf8Decoder())
.transform(LineSplitter())
.listen((line) {
buffer.write(line);
});
subscription.onDone(() {
completer.complete(buffer.toString());
});
I removed the async from the callbacks because it is not needed. All it does to make these functions async is to return a future that no-one would ever look at.
In general, the callbacks on Stream and Future should have non-async callbacks.
I also removed the subscription.cancel from the onDone event handler. If you get a "done" event, the subscription is done, there is no need to cancel it.
I also added a string buffer to avoid the quadratic time and space complexity of repeated string concatenation.
Looking at the code, you seem to be concatenating lines right after splitting them, maybe all you need is:
response.transform(Utf8Decoder()).join("").then(completer.complete);
I'll assume for now that the splitting+joining is necessary.
In that case, what I'd actually prefer to do instead is of using listen is:
var buffer = StringBuffer();
response
.transform(Utf8Decoder())
.transform(LineSplitter())
.forEach((line) {
buffer.write(line);
}).then(() {
completer.complete(buffer.toString());
}, onError: (e, s) {
completer.completeError(e, s);
});
or, if in an async function:
try {
var buffer = StringBuffer();
await for (var line in response.transform(Utf8Decoder()).transform(LineSplitter())) {
buffer.write(line);
}
completer.complete(buffer.toString());
} catch(e, s) {
completer.completeError(e, s);
}

Sequential processing of a variable number of async functions in Dart

I need to repeatedly call an asynchronous function in Dart, let's call it expensiveFunction, for a variable number of arguments. However, since each call is quite memory consuming, I cannot afford to run them in parallel. How do I force them to run in sequence?
I have tried this:
argList.forEach( await (int arg) async {
Completer c = new Completer();
expensiveFunction(arg).then( (result) {
// do something with the result
c.complete();
});
return c.future;
});
but it hasn't had the intended effect. The expensiveFunction is still being called in parallel for each arg in argList. What I actually need is to wait in the forEach loop until the expensiveFunction completes and only then to proceed with the next element in the argList. How can I achieve that?
You'll want to use a classic for loop here:
doThings() async {
for (var arg in argList) {
await expensiveFunction(arg).then((result) => ...);
}
}
There are some nice examples on the language tour.

Making a Future block until it's done

Is it possible to block a function call that returns a future?
I was under the impression calling .then() does it, but that's not what I'm seeing in my output.
print("1");
HttpRequest.getString(url).then((json) {
print("2");
});
print("3");
What I'm seeing in my output is:
1
3
2
The getString method doesn't have an async that would allow me to await it and then executes asynchronously in any case.
static Future<String> getString(String url,
{bool withCredentials, void onProgress(ProgressEvent e)}) {
return request(url, withCredentials: withCredentials,
onProgress: onProgress).then((HttpRequest xhr) => xhr.responseText);
}
How do I make it blocking without placing an infinite while loop before step 3 waiting for step 2 to be completed (not that it would work anyways due to the single thread nature of Dart)?
The above HttpRequest loads a config.json file that determines how everything works in the app, if the request for a field in the config is done before the config.json file is done loading, it causes errors, so I need to wait until the file is done loading before I allow calling getters on the fields of the class or getters needs to wait for the once-off loading of the config.json file.
Update, this is what I eventually did to make it work after Günter suggested I use a Completer:
#Injectable()
class ConfigService {
Completer _api = new Completer();
Completer _version = new Completer();
ConfigService() {
String jsonURI =
"json/config-" + Uri.base.host.replaceAll("\.", "-") + ".json";
HttpRequest.getString(jsonURI).then((json) {
var config = JSON.decode(json);
this._api.complete(config["api"]);
this._version.complete(config["version"]);
});
}
Future<String> get api {
return this._api.future;
}
Future<String> get version {
return this._version.future;
}
}
And where I use the ConfigService:
#override
ngAfterContentInit() async {
var api = await config.api;
var version = await config.version;
print(api);
print(version);
}
Now I get blocking-like functionality without it actually blocking.
There is no way to block execution until asynchronous code completes. What you can do is to chain successive code so that it is not executed before the async code is completed.
One way to chain is then
print("1");
HttpRequest.getString(url) // async call that returns a `Future`
.then((json) { // uses the `Future` to chain `(json) { print("2"); }`
print("2");
});
print("3"); // not chained and therefore executed before the `Future` of `getString()` completes.
An async call is just scheduling code for later execution. It will be added to the event queue and when the tasks before it are processed it itself will be executed. After an async call is scheduled the sync code `print("3") is continued.
In your case HttpRequest.getString() schedules a call to your server and registers (json) { print("2") as callback to be called when the response from the server arrives. Further execution of the application doesn't stall until the response arrives and there is no way to make that happen. What instead happens is that sync code is continued to be executed (print("3")).
If your currently executed sync code reaches its end, then the next scheduled task is processed the same way.
then() schedules the code (json) { print("2"); } to be executed after getString() completed.
await
async and await just make async code look more like sync code but otherwise it is quite the same and will be translated under the hood to xxx.then((y) { ... }).
I'm not sure I understand what you're trying to achieve, but it looks to me you want to do this:
myFunction() async {
print("1");
final json = await HttpRequest.getString(url);
print("2");
print("3");
}
async statement is only needed in the consumer function. In other words, producer functions doesn't need to have async, they only need to return a Future.
you should be able to do this:
Future consumerFunc() async {
print("1");
var response = await HttpRequest.getString(url);
print("2");
print("3");
}
and it should result:
1
2
3
Note: await replaces then methods

How to wait until all tasks are finished before running code

I am trying to write a multi threading search and then display all the results once the tasks have finished running but currently I don't understand how to process the results once all the tasks are complete
My code is as follows:
private async void DoSearchAsync()
{
var productResults = await SearchProductsAsync(CoreCache.AllProducts);
var brochureResults = await SearchBrochuresAsync(CoreCache.AllBrochures);
_searchResults.AddRange(productResults);
_searchResults.AddRange(brochureResults);
ResultsCount = _searchResults.Count;
}
Where _searchResults is a List<SearchResult>
My understanding is that it will do both of the awaits simultaneously and then add the products to the search results. However when I call this in my controller:
public ActionResult Index(string searchText)
{
SearchHelper helper = new SearchHelper(searchText);
helper.DoSearchAsync();
return View(helper);
}
It is displaying the page before the searches are complete so no results are showing up. How do I make it wait for the results to finish before showing the page?
I've had a look into Tasks.Wait but don't know how to apply it to the above as it expects an array of tasks
private Task<List<SearchResult>> SearchProductsAsync(IEnumerable<Product> products)
{
return Task<List<SearchResult>>.Factory.StartNew(() => GetProducts(products));
}
private Task<List<SearchResult>> SearchBrochuresAsync(IEnumerable<Assets> brochures)
{
return Task<List<SearchResult>>.Factory.StartNew(() => GetBrochures(brochures));
}
Every time you call Factory.StartNew or Task.Run inside an ASP.NET controller, you grab a thread from ThreadPool. That thread could be otherwise serving another incoming HTTP request. So, your're really hurting your web app scalability. This may be a serious issue, depending on how many concurrent HTTP requests your web app is expected to receive.
Are you OK with that? If so, the code could look like this:
private async Task DoSearchAsync()
{
var productResults = SearchProductsAsync(CoreCache.AllProducts);
var brochureResults = SearchBrochuresAsync(CoreCache.AllBrochures);
await Task.WhenAll(productResults, brochureResults);
_searchResults.AddRange(productResults.Result);
_searchResults.AddRange(brochureResultsbrochure.Results);
ResultsCount = _searchResults.Count;
}
public async Task<ActionResult> Index(string searchText)
{
SearchHelper helper = new SearchHelper(searchText);
await helper.DoSearchAsync();
return View(helper);
}
Note I changed async void to async Task for DoSearchAsync, and made your controller method async, so it returns Task<ActionResult>.
My understanding is that it will do both of the awaits simultaneously
This is not correct Pete. The await means that it will pause execution of the current method until such time that the Async method being called completes. So your 2 searches will not run in Parallel.
For clarification, see the first line of the MSDN documentation....
The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes.
You should use Task.WhenAll to wait for both searches to complete. As WhenAll supports returning Task<T> and both of your Async searches return a List<SearchResult> you can combine the results of both searches and await them both in one statement...
var searchProducts = Task.Factory.StartNew(() => GetProducts(CoreCache.AllProducts));
var searchBrochure = Task.Factory.StartNew(() => GetBrochures(CoreCache.AllBrochures));
var allResults = await Task.WhenAll(new [] { searchProducts, searchBrochure });
//allResults is List<SearchResult>[]
For completeness, its worth noting that allResults will contain 2 result sets. It does not perform a union on the 2 sets.
A complete working example for LinqPad can be found here on GitHub
You can use a task factory, then call wait on the resulting task:
Task taskA = Task.Factory.StartNew(() => DoSomeWork(10000000));
taskA.Wait();
Console.WriteLine("taskA has completed.");
http://msdn.microsoft.com/en-us/library/dd537610(v=vs.110).aspx
You can make it wait for the results to finish before displaying the page by making your function NOT be async.
Or if you want async you could move the search functions to be called by an AJAX call triggered when your page is loaded
You need to wait for the function to complete. In order to do that, first make it return a task:
private async Task DoSearchAsync()
then await it:
public async Task<ActionResult> Index(string searchText)
{
SearchHelper helper = new SearchHelper(searchText);
await helper.DoSearchAsync();
return View(helper);
}
For more information, see http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4

Resources