Cordova 无法检查 loop.How 内的 appAvailability 我可以让循环等到 appAvailability.check 执行吗?

Cordova fails in checking appAvailability inside loop.How can i make loop wait until appAvailability.check execute?

这是从我的网站加载应用程序名称的 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);

            }
        }
    }

}

console.logappAvailability.check 函数之外首先触发 n 次 在接下来的几秒内 console.logappAvailability.check 函数内部触发 n 次错误未定义appid.

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

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

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

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

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

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);
        }
    );
}