Anton23
Anton23

Reputation: 2129

Get result from async javascript method without callbacks

I have javascript function which uses CefSharp.ChroniumBrowser (WinForms). I registered "jsObject" as script object for browser: Browser.RegisterJsObject(new JsObject()). C# code:

public class JsObject
{
   //...
  public async void IsServerConnected(IJavascriptCallback callback)
  {
      var result = await Server.GetConnectionResult();
      callback.ExecuteAsync(result);
  }
}

The following js code calls C# method which asynchronously checks whether server is connected and executes callback with result.

function isServerConnected(callback) {
   window.jsObject.isServerConnected(function (connected) {
      callback(connected);
   });
}

and to get the result I should write:

isServerConnected(function(result) {
   if (result) {
      // server is connected. do something
   } else {
      // show error
   }
});

I would like to get the result in such a way:

var result = isServerConnected();
if (result){
  ...
} else {
 ...
}

Is it possible to make this work? Maybe promises should help but how I can get the result without using callbacks in the ending call: var result = isServerConnected(); ?

Upvotes: 0

Views: 997

Answers (1)

Abraham Gnanasingh
Abraham Gnanasingh

Reputation: 897

JS code doesn't execute synchronously when we use asynchronous calls. JS is very transparent on synchronous and asynchronous calls. If you are not liking callbacks, with Promises introduced in ES6, you have a better way of handling asynchronous calls. Take a look at the following code

var promise = new Promise(function(resolve, reject) {
   window.jsObject.isServerConnected(function(connected) {
      resolve(connected);
   });
});
promise.then(function(result) {
   if(result) {
      // server is connected. do something
   } else {
      // show error
   }
}).catch(function(error) {
   // catch all errors here
});

Many browsers are not yet added support for Promises. Check the browsers compatibility here. In ES7, we have async/await, which will work as you expected. Again, it is not yet added by many browsers. Check here for more on async/await.

Upvotes: 1

Related Questions