简体   繁体   English

从JavaScript中的回调函数获取结果

[英]Get the results from a callback function in Javascript

I'm writing a Javascript function which will be called by a C# application. 我正在编写一个Javascript函数,该函数将由C#应用程序调用。 I can call the function from C#, but have been unable to retrieve the result of the function. 我可以从C#调用该函数,但是无法检索该函数的结果。

So I have the following structure: 所以我有以下结构:

var B = function() {
    var A = function() {
        var dfd = new $.Deferred();
            // do something and then return the value I need
            return dfd.resolve(x);
        ......
        return dfd.promise();
    }
    $.when(A()).
        then(function(x) {
            // I can get the x I want here.
            alert(x);
            // What to do at this point?
        });
}

Since A() used asynchronous methods, I chose to use jQuery.promise() method to ensure I get the final result of A() . 由于A()使用异步方法,因此我选择使用jQuery.promise()方法以确保获得A()的最终结果。 Now I want B() to return the value x to the C# application. 现在,我希望B()将值x返回给C#应用程序。 Is there any good solution to this? 有什么好的解决办法吗?

I assume that you've called your Javascript function by calling WebView method InvokeScriptAsync with Js function name as a parameter. 我假设您已经通过使用Js函数名称作为参数调用WebView方法InvokeScriptAsync来调用Javascript函数。

The problem here is that your JavaScript function is an asynchronous since it uses promise - so you cannot simply get its return value on C#. 这里的问题是您的JavaScript函数是异步的,因为它使用了promise-因此您不能简单地获取C#的返回值。 The IAsyncOperation ends as the promise object has been returned, not as it has been resolved. IAsyncOperation在返回了Promise对象时结束,而不是因为它已解决。

If your javascript function was synchronious: 如果您的javascript函数是同步的:

The return value of the InvokeScriptAsync function is the string result of the script invocation - so if you'll wait for it you'll get the result. InvokeScriptAsync函数的返回值是脚本调用的字符串结果-因此,如果您等待它,则将得到结果。

MSDN documentation : https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx?f=255&MSPPError=-2147217396 MSDN文档: https : //msdn.microsoft.com/zh-cn/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx?f=255&MSPPError=-2147217396

However, you can always invoke webView event by calling windows.external.invoke with string parameter from JavaScript and get it on C# by subscribing to webView ScriptNotify event. 但是,您始终可以通过从JavaScript调用带有字符串参数的windows.external.invoke来调用webView事件,并通过订阅webView ScriptNotify事件在C#上获取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM