Click here to Skip to main content
15,916,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I'm stuck with this asynchronous execution of javascript.

JavaScript
var rowCollection = [];
var headerCollection = ["Formula 1", "Formula 2", "Formula 3", "Formula 4", "Formula 5", "Formula 6", "Formula 7"];
var currentFormulaValues = {};
//var finalCollection = 
function generate(){

	for(var i=0;i<headerCollection.length;i++){

		calculateFormulaValue(i,headerCollection[i]);
        console.log("current index" +i + " -->" +headerCollection[i]);
  

    }
}

function calculateFormulaValue(j,currentFormula){
  
    //Some common code which need to run ..

    if(currentFormula == "Formula 1"){
        var promise = new Promise(function(resolve, reject) {
		var request = new XMLHttpRequest();

		request.open('GET', 'https://api.icndb.com/jokes/random');
		request.onload = function() {
		  if (request.status == 200) {
			resolve(request.response);
		  } else {
            
			reject(Error(request.statusText));
		  }
		};
		
		request.onerror = function() {reject(Error('Error fetching data.')); 
		};

		request.send();
	  });
	  
	  promise.then(function(data) {
        
        currentFormulaValues[currentFormula] = JSON.parse(data).value.id;
		//rowCollection[j] = JSON.parse(data).value.id;
        
        console.log("j - " + j +" ->" + (JSON.stringify(currentFormulaValues)));
	  }, function(error) {
		console.log('Promise rejected.');
	  });
    }
  
    else if(currentFormula == "Formula 2"){
        var promise = new Promise(function(resolve, reject) {
		var request = new XMLHttpRequest();

		request.open('GET', 'https://api.icndb.com/jokes/random');
		request.onload = function() {
		  if (request.status == 200) {
			resolve(request.response);
		  } else {
            
			reject(Error(request.statusText));
		  }
		};
		
		request.onerror = function() {reject(Error('Error fetching data.')); 
		};

		request.send();
	  });
	  
	  promise.then(function(data) {
        currentFormulaValues[currentFormula] = JSON.parse(data).value.id;
		//rowCollection[j] = JSON.parse(data).value.id;
        console.log("j - " + j +" ->" + (JSON.stringify(currentFormulaValues)));
       
	  }, function(error) {
		console.log('Promise rejected.');
	  });
    }
  
    // for all other formulas
  
    else{
        var promise = new Promise(function(resolve, reject) {
		var request = new XMLHttpRequest();

		request.open('GET', 'https://api.icndb.com/jokes/random');
		request.onload = function() {
		  if (request.status == 200) {
			resolve(request.response);
		  } else {
            
			reject(Error(request.statusText));
		  }
		};
		
		request.onerror = function() {reject(Error('Error fetching data.')); 
		};

		request.send();
	  });
	  
	  promise.then(function(data) {
        
        currentFormulaValues[currentFormula] = JSON.parse(data).value.id;
		//rowCollection[j] = JSON.parse(data).value.id;
        console.log("j - " + j +" ->" + (JSON.stringify(currentFormulaValues)));
        
	  }, function(error) {
		console.log('Promise rejected.');
	  });
         
    }
        
     if(j == headerCollection.length-1){
        console.log("SAVE FINAL")
        rowCollection.push(currentFormulaValues);
        console.log(JSON.stringify(currentFormulaValues))
      } 
}



I used some sample API for this demo. click run and see jsbin output console. Save running before all formulas are generated.

JS Bin - Collaborative JavaScript Debugging[^]


After I have generated all formulas only I have push it into my row collection finally.

How do I achieve this ?

What I have tried:

I tried create Immediate invoking function inside for loop as suggested on <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Closures".. N[^]

Still no luck.. please help on this.
Posted
Updated 24-Dec-16 21:21pm

1 solution

XMLHttpRequest.open() has a 3rd parameter (and 4th and 5th too, but it is irrelevant to you for now), that sets if the call should be asynchronous or synchronous... Use it to wait for the answers from the server...
XMLHttpRequest.open() - Web APIs | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900