How to provide `Context` to async functions - asynchronous

I am trying call the poll_flush method, which requires a Context object. I wonder how to obtain such object in tokio runtime?

You don't call poll_* methods yourself unless you're writing a runtime, let the runtime do it for you using await on the corresponding async functions. Instead of calling poll_flush you should be calling AsyncWriteExt::flush().await.

Related

F#: How can I wrap a non-async value in Async<'T>?

In F#, I'm implementing an interface that returns Async<'T>, but my implementation does not require any async method calls. Here's an example of my current implementation:
type CrappyIdGeneratorImpl() =
interface IdGenerator with
member this.Generate(): Async<Id> = async {
return System.Guid.NewGuid().ToString()
}
Is this the "best" way to wrap a non-Async<> value in Async<>, or is there a better way?
Put another way, I'm looking for the Async equivalent of System.Threading.Tasks.Task.FromResult().
Yes, that's the best way.
Note that, as stated in the comment, another way would be to do async.Return but it's not exactly the same thing, and in your use case it won't work, due to eager evaluation of the argument.
In your case you're interested in calling the .NewGuid() method each time the async is run, but if you use async.Return alone it will be evaluated once and the async computation will be created with that result as a fixed value.
In fact the equivalent of the CE is async.Delay (fun () -> async.Return (.. your expression ..))
UPDATE
As Tarmil noted, this can be interpreted as intended, given that the code resides in a method.
It might be the case that you created a method because that's the way you do with tasks, but Asyncs can be created and called independently (hot vs cold async models).
The question of whether the intention is delaying the async or creating an async at each method call is not entirely clear to me, but whichever is the case, the explanation above about each approach is still valid.

Why do functions have to be async in order to use await within them?

If I want to await a function, why does that have to be done in an async function only?
If I have this:
Function myFunc() {
return await myOtherFunc();
}
I get an error saying: “await expression is only allowed within an asynchronous function.”
I can understand if myOtherFunc() had to be asynchronous (it doesn't make sense to await an asynchronous function), but why does it care if the calling function is asynchronous or not. You can have a fork in a process within a synchronous function due to a call to an asynchronous function, right? So then why can’t you await that asynchronous function within the synchronous function?
NOTE: my question is NOT a duplicate of Javascript Await/Async Feature - What if you do not have the await word in the function?.
^ that question is asking what happens if await is not used in an async function. I'm asking why the function has to be async in order to use await. My response to DougBug below explains why they are different.
The picture in the following article might help explain it to you a bit.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/index
The basic idea though is that the async keyword allows the function to yield its execution up to a calling function.
As such any function that implements await must be marked async so that it can traverse back up the calling path until the first caller is only waiting on it to complete what it needs to do.

Meteor wrapAsync syntax

How do I use the Meteor wrapAsync?
Below is what I am trying to do
if (tempTreatment.groupId === undefined) {
// create new group
Meteor.wrapAsync(Meteor.call('createTreatmentGroup', salon, tempTreatment.groupName, tempTreatment.groupName));
// get group id
var getGroup = Meteor.wrapAsync(Meteor.call('getTreatmentGroup', salon, tempTreatment.groupName));
console.log(getGroup);
tempTreatment.groupId = getGroup._id;
}
I want to run these two Meteor.callfunctions synchronosly but I get undefined on console.log(getGroup); which shuold just return an object.
Meteor.wrapAsync is a server-side API designed to wrap Node.js asynchronous functions requiring a callback as last argument, to make them appear synchronous through the use of Futures, a Fibers sub-library. (more on this here : https://www.discovermeteor.com/blog/wrapping-npm-packages/)
It is not intended to be used client-side to turn asynchronous Meteor.call into a synchronous call because on the browser, Remote Method Invokation calls are ALWAYS asynchronous.
Long story short, you simply cannot achieve what you're trying to do, you have to use callbacks and nest your second method call inside the success callback of your first method call.

SignalR .Net client - how to invoke synchronously and asynchronously

I'm learning SignalR using the .Net client (not javascript), and was hoping for some clarification on how to invoke hub proxy methods in a synchronous or asynchronous manner.
Method with no return value
So far I've been doing something like this:-
myHubProxy.Invoke("DoSomething");
I've found this to be asynchronous, which is fine as it's effectively "fire-and-forget" and doesn't need to wait for a return value. A couple of questions though:-
Are there any implications with wrapping the Invoke in a try..catch block, particularly with it being asynchronous? I might want to know if the call failed.
Are there any scenarios where you would want to call a method that doesn't return a value synchronously? I've seen the .Wait() method mentioned, but I can't think why you would want to do this.
Method with return value
So far I've been using the Result property, e.g.:-
var returnValue = myHubProxy.Invoke<string>("DoSomething").Result;
Console.WriteLine(returnValue);
I'm assuming this works synchronously - after all, it couldn't proceed to the next line until a result had been returned. But how do I invoke such a method asynchronously? Is it possible to specify a callback method, or should I really be using async/await these days (something I confess to still not learning about)?
If you want to write asynchronous code, then you should use async/await. I have an intro on my blog with a number of followup resources at the end.
When you start an asynchronous operation (e.g., Invoke), then you get a task back. The Task type is used for asynchronous operations without a return value, and Task<T> is used for asynchronous operations with a return value. These task types can indicate to your code when the operation completes and whether it completed successfully or with error.
Although you can use Task.Wait and Task<T>.Result, I don't recommend them. For one, they wrap any exceptions in an AggregateException, which make your error handling code more cumbersome. It's far easier to use await, which does not do this wrapping. Similarly, you can register a callback using ContinueWith, but I don't recommend it; you need to understand a lot about task schedulers and whatnot to use it correctly. It's far easier to use await, which does the (most likely) correct thing by default.
The .Result property returns a async Task, so the server requests is still performed async.
There is not reason to hold up a thread for the duration of the call thats why you use async.
If you fire the call on the GUI thread its even more important todo it async because otherwise the GUI will not respond while the call is done
1) Yuo need to use the await keyword if you want try catch blocks to actually catch server faults. Like
try
{
var foo = await proxy.Invoke<string>("Bar");
}
catch (Exception ex)
{
//act on error
}
2) I think you ment to ask if its any reason to call it async? And yes like I said, you do not want to block any threads while the request is being made

AS3 - How to do a synchronous load of an asynchronous call?

I have a function that loads a user object from a web service asynchronously.
I wrap this function call in another function and make it synchronous.
For example:
private function getUser():User{
var newUser:User;
var f:UserFactory = new UserFactory();
f.GetCurrent(function(u:User):void{
newUser = u;
});
return newUser;
}
UserFactory.GetCurrent looks like this:
public function GetCurrent(callback:Function):void{ }
But my understanding is there is no guarantee that when this function gets called, newUser will actually be the new user??
How do you accomplish this type of return function in Flex?
This way madness lies.
Seriously, you're better off not trying to force an asynchronous call into some kind of synchronous architecture. Learn how the event handling system works in your favour and add a handler for the result event. In fact, here's the advice straight from the flexcoders FAQ :
Q: How do I make synchronous data calls?
A: You CANNOT do synchronous calls. You MUST use the result event. No,
you can't use a loop, or setInterval or even callLater. This paradigm is
quite aggravating at first. Take a deep breath, surrender to the
inevitable, resistance is futile.
There is a generic way to handle the asynchronous nature of data service
calls called ACT (Asynchronous Call Token). Search for this in
Developing Flex Apps doc for a full description.
See my answer here:
DDD and Asynchronous Repositories
Flex and Flash Remoting is inherently asynchronous so fighting against that paradigm is going to give you a ton of trouble. Our service delegates return AsyncToken from every method and we've never had a problem with it.
If you want to ensure that the application doesn't render a new view or perform some other logic until the result/fault comes back, you could do the following:
Attach an event listener for a custom event that will invoke your "post result/fault code"
Make the async call
Handle the result/fault
Dispatch the custom event to trigger your listener from #1
Bear in mind this going to lead to a lot of annoying boilterplate code every time you make an async call. I would consider very carefully whether you really need a synchronous execution path.
You can't convert async call into sync one without something like "sleep()" function and as far as I know it is missing in AS3. And yes, it is not guaranteed that newUser would contain user name before return statement.
The AS3 port of the PureMVC framework has mechanisms for implementing synchronous operations in a Model-View-Controller context. It doesn't try to synchronize asynchronous calls, but it lets you add a synchronous application pattern for controlling them.
Here's an example implementation: PureMVC AS3 Sequential Demo.
In this example, five subcommands are run sequentially, together composing a whole command. In your example, you would implement getUser() as a command, which would call commandComplete() in the getURL() (or whatever) callback. This means the next command would be certain that the getUser() operation is finished.

Resources