SignalR function return value
Asked Answered
T

2

9

I created a SignalR hub which contain the following hub function:

public bool GetStatus()
{
    return true;
}

I'm want to call this function from my JS code and get the request of this call. Something like this:

var result = hub.server.getStatus();
if (result)
    alert('success');

Is this possible without returning Task of bool?

Thank you.

Tightlipped answered 27/10, 2014 at 18:34 Comment(5)
what do you mean by returning Task?Resort
do you want it to return anything?Resort
There is a option to return Task, which makes the whole process async. This what I'm want to avoid.Tightlipped
I don't think you HAVE to return anything. We use signalR and we don't return anything. Maybe I don't understand the whole thing.Resort
this doesn't make sense. Hubs don't have return values, they make calls to clients.Meiosis
S
27

No. The SignalR JavaScript client is non-blocking; you will need to follow the Promise interface, like so:

hub.server.getStatus().done(function(result) { 
    if (result) {
        alert('success'); 
    }
});
Sekyere answered 27/10, 2014 at 18:45 Comment(2)
I note it isn't an actual JavaScript Promise<T> but SignalR's own promise type (otherwise it would be called then, not done).Yukoyukon
UPDATE: Ah, SignalR uses JQueryPromise<T> which is documented here: definitelytyped.org/docs/toastr--toastr/interfaces/…Yukoyukon
G
2

On the client side you'll need to use the promise interface. but on the server side it's entirely up to you, the code below is from the SignalR guide site:

Synchronous

public IEnumerable<Stock> GetAllStocks()
{
        // Returns data from memory.
        return _stockTicker.GetAllStocks();
}

Asynchronous

public async Task<IEnumerable<Stock>> GetAllStocks()
{
    // Returns data from a web service.
    var uri = Util.getServiceUri("Stocks");
    using (HttpClient httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync(uri);
        return (await response.Content.ReadAsAsync<IEnumerable<Stock>>());
    }
}

Just change the server signature according to your needs

Glenda answered 17/3, 2016 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.