0

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(); ?

1
  • This feels like it's an XY Problem - why do you want it to be a synchronous call - usually async/callbacks are the way to go in JS. Promises sort of just hide the callbacks away a little - it's still an async call. Commented Jul 14, 2017 at 10:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I will try to use async/await if it is supported in the latest version of Cef Chronium Browser. Thanks for ideas!
FYI, I removed arrow functions in the code as it is not yet supported by some browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.