JS - 强制函数在其他函数之后运行

时间:2015-02-05 01:25:39

标签: javascript jquery

我正在构建一个JS脚本,它将从JSON获取某些ID,显示这些ID,然后从数组中删除找到的ID,然后转到下一个函数,这将测试其他值。

我的问题是第二个函数中的代码在第一个函数完成之前进行评估并导致完整数组出现,而不是在第一个函数完成后使用删除的值更新的数组。

你可以在我的控制台日志中看到第126行的第一行(num =)在调用erase函数之前计算,即使第126行在第二个函数内并且还没有被调用。

num=,111,222,8378102505047 - ScriptNewID.js:126 ["111", "222", "8378102505047"]- ScriptNewID.js:220 ["111", "222"] ScriptNewID.js:221

在第一个函数完成之前,我怎么能强制不评估这些值?

提前致谢!

// Version 1

	getEmptyArticles();

function getEmptyArticles() {
	
	articleArray = [];
	
	var empytyBaseURL = "scripts/get-empty-rows.php";

			$.ajax({
				url: empytyBaseURL,
				dataType: 'json',
				timeout: 7000
			}).done(function(json){
				token = json;
					for( var i = 0; i < token.length; i++) {
					articleArray.push(token[i]);
					}
				API1(articleArray);
				API2(articleArray);
				
			}).fail(function(){
				alert("ERROR: Could Not Get Empty Articles");
			}).always(function() {
				//setTimeout(getEmptyArticles, 200000);
				//articleArray.length = 0;
			});		
			
 }
 
function API1(articleIDs) {

	var BaseURL = "OMITTED";
	var IDs =  returnCIDs(articleIDs, ";");
	var APIKey = "OMITTED";
	var APIURL = BaseURL + IDs + "?api_key=" + APIKey;
				
		$.ajax({
			url: APIURL,
			dataType: 'json',
			timeout: 7000
		}).done(function(json){
			token = json;
			obj = token.result;
			API1Success(obj);
		}).fail(function(){
			API1Error();
		});	
	
		function API1Success(obj) {
			var lastScan = "";
			
				for (var i = 0; i < obj.length; i++) {
					if(obj[i].LabelNo) {
						//ADD RESULTS TO TABLE HERE
					} else if (obj[i].LabelNumber) {
						var arrayIndex = articleArray.indexOf(obj[i].LabelNumber);
							for (var x = 0; x < obj[i].Scans.length; x++) {
								lastScan = obj[i].Scans[x].StatusDescription;	
							}
						
				//POST DATA TO TABLE 1 DATABASE URL 
												
						var id = obj[i].LabelNumber;
						lastScan = lastScan.replace(/'/g, "");
						var articles = "None Specified";
						var Name = "OMITTED";
						
						postTable1Data(id, lastScan, articles, Name);					
				
				//POST DATA TO TABLE 2 DATABASE URL
					
						for (var x = 0; x < obj[i].Scans.length; x++) {
							var eventID = obj[i].LabelNumber;
							var eventProdType = "";
							var eventBadTime = moment(obj[i].Scans[x].Date, "DD/MM/YYYY HH:mm:ss");
							var eventGoodTime = eventBadTime.format("YYYY-MM-DD HH:mm:ss");
							var eventLocation = obj[i].Scans[x].Name;
							var scan = obj[i].Scans[x].StatusDescription;
							scan = scan.replace(/'/g, "");
							
							postTable2Data(eventID, eventProdType, eventGoodTime, eventLocation, scan);
						}
				
				//REMOVE GOOD URL FROM ARRAY
					eraseFoundArticle(obj[i].LabelNumber);
					}
				}

		}

		function API1Error() {
			console.log("ERROR CONNECTING TO THE API");
		}	
}

function API2(articleIDs) {

	
	var tPHPURL = "omitted";
	var tIDs =  "num=" + returnCIDs(articleIDs, ",");
	
	$.ajax({
		type: "POST" ,
		url: tPHPURL ,
		data: tIDs
		}).done(function(json){
			obj = json;
			tSuccess(obj);
		}).fail(function(){
			tError();
		});	
	
	function tSuccess(obj) {
						
							
		//ERROR LOGGING
		
		if (obj.errors.length > 1) {
			for (var i = 0; i < obj.errors.length; i++) {
				
				var errors = obj.errors[i];
				var strErrors = errors.split(" ");
				var id = strErrors[1];
				var c = "omitted";
				
				postErrorData(id, c)
				
			}
		}
		
		//SUCCESS LOGGING
		
		for (var i = 0; i < obj.tatConnotes.length; i++) {
			var id = obj.tatnotes[i].connote;
			var status = obj.tatConnotes[i].lastEventStatus;
			var articles = obj.tatConnotes[i].actualItems;
			var cName = obj.tatConnotes[i].tBusinessName;
			
			eraseFoundArticle(id);

			
			postTable1Data(id, status, articles, cName);

				for (var x = 0; x < obj.tatnotes[i].cEvents.length; x++) {
					var cId = obj.tatnotes[i].cEvents[x].connote;
					var cType = obj.tatnotes[i].cDescription;
					var badDateTime = moment(obj.tatConnotes[i].cEvents[x].eventDateTime, "ddd D/MM/YYYY hh:mm A");
					var cDateTime = badDateTime.format("YYYY-MM-DD HH:mm:ss");
					var cLocation = obj.tatnotes[i].cEvents[x].location;
					var cDescription = obj.tatnotes[i].consignmentEvents[x].eventDescription;
					
					postTable2Data(cId, cType, cDateTime,cLocation ,cDescription);
				}
		
		}
	

	}
	
	function tError() {
		//ADD BACKUP FUNCTION HERE
	}

}

function postTable1Data(id, status, articles, couriername) {
			$.ajax({
				type: "POST",
				url: "scripts/update.php",
				data: //INSERT DATA HERE - OMITTED
				success: //INSERT DATA HERE - OMITTED
			});		
	}

function postTable2Data(id, type, datetime, location, description) {

			$.ajax({
				type: "POST",
				url: "scripts/update.php",
				data: //INSERT DATA HERE - OMITTED
				success: //INSERT DATA HERE - OMITTED
			});	

	}
	
function postErrorData(id, courier) {
		
		//POST ERROR DATA - OMITTED
		
	}
		
function eraseFoundArticle(id) {
		var arrayIndex = articleArray.indexOf(id);
			articleArray.splice(arrayIndex,1);

	}
		

function returnCIDs(articleIDs, seperator) {
			var cArticleIDs = "";
			for (var i = 0; i < articleIDs.length; i++) {	
				var cArticleIDs = cArticleIDs + seperator + articleIDs[i] ;
			}
			return cArticleIDs;
}

1 个答案:

答案 0 :(得分:1)

试试这个(未经测试)。在API1完成之前,它不会调用API2:

// Version 1

    getEmptyArticles();

function getEmptyArticles() {

    articleArray = [];

    var empytyBaseURL = "scripts/get-empty-rows.php";

            $.ajax({
                url: empytyBaseURL,
                dataType: 'json',
                timeout: 7000
            }).done(function(json){
                token = json;
                    for( var i = 0; i < token.length; i++) {
                    articleArray.push(token[i]);
                    }
                API1(articleArray);

            }).fail(function(){
                alert("ERROR: Could Not Get Empty Articles");
            }).always(function() {
                //setTimeout(getEmptyArticles, 200000);
                //articleArray.length = 0;
            });     

 }

function API1(articleIDs) {

    var BaseURL = "OMITTED";
    var IDs =  returnCIDs(articleIDs, ";");
    var APIKey = "OMITTED";
    var APIURL = BaseURL + IDs + "?api_key=" + APIKey;

        $.ajax({
            url: APIURL,
            dataType: 'json',
            timeout: 7000
        }).done(function(json){
            token = json;
            obj = token.result;
            API1Success(obj, articleIDs);
        }).fail(function(){
            API1Error();
        }); 

        function API1Success(obj, articleIDs) {
            var lastScan = "";

                for (var i = 0; i < obj.length; i++) {
                    if(obj[i].LabelNo) {
                        //ADD RESULTS TO TABLE HERE
                    } else if (obj[i].LabelNumber) {
                        var arrayIndex = articleArray.indexOf(obj[i].LabelNumber);
                            for (var x = 0; x < obj[i].Scans.length; x++) {
                                lastScan = obj[i].Scans[x].StatusDescription;   
                            }

                //POST DATA TO TABLE 1 DATABASE URL 

                        var id = obj[i].LabelNumber;
                        lastScan = lastScan.replace(/'/g, "");
                        var articles = "None Specified";
                        var Name = "OMITTED";

                        postTable1Data(id, lastScan, articles, Name);                   

                //POST DATA TO TABLE 2 DATABASE URL

                        for (var x = 0; x < obj[i].Scans.length; x++) {
                            var eventID = obj[i].LabelNumber;
                            var eventProdType = "";
                            var eventBadTime = moment(obj[i].Scans[x].Date, "DD/MM/YYYY HH:mm:ss");
                            var eventGoodTime = eventBadTime.format("YYYY-MM-DD HH:mm:ss");
                            var eventLocation = obj[i].Scans[x].Name;
                            var scan = obj[i].Scans[x].StatusDescription;
                            scan = scan.replace(/'/g, "");

                            postTable2Data(eventID, eventProdType, eventGoodTime, eventLocation, scan);
                        }

                //REMOVE GOOD URL FROM ARRAY
                    eraseFoundArticle(obj[i].LabelNumber);
                    }
                }
            API2(articleIDs);

        }

        function API1Error() {
            console.log("ERROR CONNECTING TO THE API");
        }   

}

function API2(articleIDs) {


    var tPHPURL = "omitted";
    var tIDs =  "num=" + returnCIDs(articleIDs, ",");

    $.ajax({
        type: "POST" ,
        url: tPHPURL ,
        data: tIDs
        }).done(function(json){
            obj = json;
            tSuccess(obj);
        }).fail(function(){
            tError();
        }); 

    function tSuccess(obj) {


        //ERROR LOGGING

        if (obj.errors.length > 1) {
            for (var i = 0; i < obj.errors.length; i++) {

                var errors = obj.errors[i];
                var strErrors = errors.split(" ");
                var id = strErrors[1];
                var c = "omitted";

                postErrorData(id, c)

            }
        }

        //SUCCESS LOGGING

        for (var i = 0; i < obj.tatConnotes.length; i++) {
            var id = obj.tatnotes[i].connote;
            var status = obj.tatConnotes[i].lastEventStatus;
            var articles = obj.tatConnotes[i].actualItems;
            var cName = obj.tatConnotes[i].tBusinessName;

            eraseFoundArticle(id);


            postTable1Data(id, status, articles, cName);

                for (var x = 0; x < obj.tatnotes[i].cEvents.length; x++) {
                    var cId = obj.tatnotes[i].cEvents[x].connote;
                    var cType = obj.tatnotes[i].cDescription;
                    var badDateTime = moment(obj.tatConnotes[i].cEvents[x].eventDateTime, "ddd D/MM/YYYY hh:mm A");
                    var cDateTime = badDateTime.format("YYYY-MM-DD HH:mm:ss");
                    var cLocation = obj.tatnotes[i].cEvents[x].location;
                    var cDescription = obj.tatnotes[i].consignmentEvents[x].eventDescription;

                    postTable2Data(cId, cType, cDateTime,cLocation ,cDescription);
                }

        }


    }

    function tError() {
        //ADD BACKUP FUNCTION HERE
    }

}

function postTable1Data(id, status, articles, couriername) {
            $.ajax({
                type: "POST",
                url: "scripts/update.php",
                data: //INSERT DATA HERE - OMITTED
                success: //INSERT DATA HERE - OMITTED
            });     
    }

function postTable2Data(id, type, datetime, location, description) {

            $.ajax({
                type: "POST",
                url: "scripts/update.php",
                data: //INSERT DATA HERE - OMITTED
                success: //INSERT DATA HERE - OMITTED
            }); 

    }

function postErrorData(id, courier) {

        //POST ERROR DATA - OMITTED

    }

function eraseFoundArticle(id) {
        var arrayIndex = articleArray.indexOf(id);
            articleArray.splice(arrayIndex,1);

    }


function returnCIDs(articleIDs, seperator) {
            var cArticleIDs = "";
            for (var i = 0; i < articleIDs.length; i++) {   
                var cArticleIDs = cArticleIDs + seperator + articleIDs[i] ;
            }
            return cArticleIDs;
}