作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是从我的网站加载应用程序名称的 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.log
在 appAvailability.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/
这是从我的网站加载应用程序名称的 getapps 函数。 getapps = function (applist){ var xmlhttp = new XMLHttpRequest(); var
我是一名优秀的程序员,十分优秀!