Javascript:监听回调返回

标签 javascript uwp async-await

我正在使用 Javascript 创建 UWP 应用。我需要将一些代码从 C# 转换为 javascript。
我正在关注这个Documentation关于如何添加应用内购买。

C# 中的需要代码如下所示:

async void BuyFeature()
{
    if (!licenseInformation.ProductLicenses["featureName"].IsActive)
    {
        try
        {
            // The customer doesn't own this feature, so
            // show the purchase dialog.
            await CurrentAppSimulator.RequestProductPurchaseAsync("featureName", false);

            //Check the license state to determine if the in-app purchase was successful.
        }
        catch (Exception)
        {
            // The in-app purchase was not completed because
            // an error occurred.
        }
    }
    else
    {
        // The customer already owns this feature.
    }
}

正如您在第 9 行中看到的,有一个等待函数。我如何将其翻译成 JavaScript?

所以在调用 javascript 之后...

function abc() {
    Windows.ApplicationModel.Store.CurrentAppSimulator.requestProductPurchaseAsync("1", false);
    // something fancy here ... but that needs to wait
};

...我需要等到它返回一些内容,然后继续执行该函数。

最佳答案

根据你的描述。我想您的问题是如何在 UWP 中通过 JavaScript 使用异步函数。

In many cases, calling an asynchronous function is almost as simple as calling a conventional function. The difference is that you use the then or the done method to assign the handlers for results or errors and to start the operation.

所以你可以使用RequestProductPurchaseAsync在 JavaScript 中,如下所示。请备注RequestProductPurchaseAsync(System.String,System.Boolean) Windows 8.1 之后的版本可能会更改或不可用。相反,使用 RequestProductPurchaseAsync(System.String) .

function abc() {
    Windows.ApplicationModel.Store.CurrentAppSimulator.requestProductPurchaseAsync("1").done(
        function (purchaseResults) {
            //TODO - purchaseResults is the return of requestProductPurchaseAsync method
        },
        function () {
            console.log("error: Unable to buy 1.");
        });
}

更多信息请参见 Asynchronous patterns in UWP using JavaScript以及如何使用 CurrentAppSimulator ,您可以引用Trial app and in-app purchase sample .

关于Javascript:监听回调返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438506/

相关文章:

javascript - 是否使用了指令的链接函数的返回值?

javascript - 挣扎于 jQuery Toggle 函数

c# - 在 C# UWP Windows 10 应用程序中读取和写入 Excel 工作表

c# - 如何在 UWP 应用程序中获取当前在 Azure VM 中运行的进程列表

javascript - 如果没有更新,如何停止接收更新?

javascript - JScript/VBScript 错误

c# - 在 UWP 下,GetRectFromCharacterIndex 不会返回根据控件样式调整的值

C# 任务在 Task.WhenAll 之前执行

javascript - nodejs 中的 Promises 和 async/await

C#有异步函数调用同步函数或者同步函数调用异步函数