我正在使用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
};
......我需要等到它返回一些内容然后继续执行该功能。
答案 0 :(得分:2)
根据你的描述。我想你的问题是如何在UWP中使用JavaScript的异步函数。
在许多情况下,调用异步函数几乎与调用常规函数一样简单。不同之处在于您使用then或done方法为结果或错误分配处理程序并开始操作。
因此,您可以在JavaScript中使用RequestProductPurchaseAsync,如下所示。请注意,在Windows 8.1之后,RequestProductPurchaseAsync(System.String,System.Boolean)可能会被更改或不可用于发布。相反,请使用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。
答案 1 :(得分:1)
我认为你正在寻找的是使用承诺,或许这样的事情:
function productPurchaseAsyncCallExample(){
return {response:'test response',errorCode:'ok/fail etc..'};
// or whatever the response is...
}
var requestProductPurchaseAsync = new Promise(function(resolve, reject){
//We call resolve(...) when what we were doing async succeeded, and reject(...) when it failed.
//In this example, we use setTimeout(...) to simulate async code.
//In reality, you will probabally using something like XHR or an HTML5 API.
//setTimeout(function(){
// resolve({success:'yes', bool:true}); //Yay! Everything went well!
//}, 2250);
resolve(productPurchaseAsyncCallExample());
});
function BuyFeature() {
if (true){ // your if statement check
requestProductPurchaseAsync.then(function(data){
console.log(data);
// do the rest
});
}
};
BuyFeature();
答案 2 :(得分:0)
function abc() {
var ans=testFn('a','b'); // let testFn is your function and assume it returns 'txt'
while(ans!="txt"){}
//do rest of code
}