gpt4 book ai didi

javascript - Cordova 无法检查循环内的 appAvailability。如何让循环等待 appAvailability.check 执行?

转载 作者:行者123 更新时间:2023-11-30 00:25:03 25 4
gpt4 key购买 nike

这是从我的网站加载应用程序名称的 getapps 函数。

getapps = function (applist){   
var xmlhttp = new XMLHttpRequest();
var url = "http://mywebsite.com/"+applist;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(data) {
var i;
var query = data.data;
if(query != ''){
for(i = 0; i < query.length; i++) {
var appinstall='';
appAvailability.check(
query[i].appid, // URI Scheme or Package Name
function() { // Success callback
appinstall = "is available :)";
console.log(query[i].appid+"is available :)");
},
function() { // Error callback
appinstall = "is not available :(";
console.log(query[i].appid+"is not available :(");
}
);
console.log(appinstall);

}
}
}

}
appAvailability.check 函数之外的

console.log 首先触发 n 次 在接下来的几秒内 console.logappAvailability.check函数启动 n 次并出现错误 undefined appid。

我通过删除 for 循环和预定义 appid 进行了测试,效果非常好,没有错误。

如何通过让循环等待 appAvailability.check 完成来解决这个问题?

最佳答案

因为appAvailability.check执行成功和失败的回调。

我强烈怀疑您的代码正在该回调中进行 native 调用,该回调在您的回调执行后运行该回调。

您可以使用递归来解决这个问题,如下所示:

function getApps(appslist) {
var xmlhttp = new XMLHttpRequest(),
url = "http://mywebsite.com/"+applist;

callback = callback || function() {};

xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);

if (data != ''){
checkApp(data.data);
}
}
}

xmlhttp.open("GET", url, true);
xmlhttp.send();
}

function checkApp(applist, callback) {
var app = applist.push();

if (!app) {
callback();
return;
}

appAvailability.check(
app.appid, // URI Scheme or Package Name
function() { // Success callback
console.log(app.appid + "is available");

// handle availability here

checkApp(applist, callback);
},
function() { // Error callback
console.log(app.appid + "is not available");

// handle absence here

checkApp(applist, callback);
}
);
}

关于javascript - Cordova 无法检查循环内的 appAvailability。如何让循环等待 appAvailability.check 执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31745464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com