我正在使用 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/