How can i prevent a function to be fired before the execution of an other

45 Views Asked by At

i use a function to extract data from an XMLhttprequest, this data is pushed to a variable array outside of the main async function, everthing works for this part, but when i call this function, events that comes after are fired before the function has finished running even if i put an await before, resulting with an empty array because the event that is fired is a redirection (ctx.response.redirect) that calls a route function which retrieves the array variable ... with other words i use an external variable array to pass data from one to another route function, but the route function that should grab the variable array is fired before the array is filled. how can i make this code awaiting for the function is finished before running the event that follows

Here is the code :

the route function where i extract and push data from an XMLhttprequest to an external variable array

const validateSHipping = async(ctx:any)=>{
        const body = await ctx.request.body({type: 'form-data'});
        const product =  await body.value.read();
        if(!ctx.request.hasBody){
            ctx.response.status = 400;
             ctx.response.body ={
                 success: false,
                 msg: 'No data'}
          
        }else{
            try{
    
    
                
               let shipFunction = async(inData:any,inMethod:string,inUrl:string,inArray:boolean,serviceName:string)=>{
    
                
                    var xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    
                    xhr.addEventListener("readystatechange", function () {
                       
                        if (this.readyState === 4) {
                            
                            var response = xhr.responseText;
                            var jsonResponse = JSON.parse(response);
                            
                            if(inArray == true){  
                         
                            }else if(inArray == false){
                                
                               if(inUrl === `https://api.laposte.fr/controladresse/v2/adresses?q=${okapiAdress}`){
                                    console.log('-- okapiAdress ---');
                                    const jsonResponseLength = jsonResponse.length;
                                    for(let i = 0; i < jsonResponseLength; i++){
                                        adressesFound.push(jsonResponse[i].adresse);
                                    }  
                                   
                                }
                                
                            }
      
                                
                        }
                    
                    });

                    xhr.open(inMethod,inUrl);
    
                    if(serviceName ==='Okapi'){
                        xhr.setRequestHeader("Content-Type", "application/json");
                        xhr.setRequestHeader("X-Okapi-Key", "ZLd3/5PZpfN4bwSQ8qiwVK25ZqC61XHCtZmuV33dpWnTO0/uOplAL+PpNTjYeMi0");  
                    }

                    if(inMethod === "GET"){
                        xhr.send();
                    }else if(inMethod === "POST"){
                        xhr.send(inData);
                    }
                    
                
                }
    
                
               await shipFunction(null,"GET",`https://api.laposte.fr/controladresse/v2/adresses?q=${okapiAdress}`,false,"Okapi");
                    
                    
               ctx.cookies.set('adressValidation','true');
               ctx.response.redirect('/OBV/panier'); // Redirection 
    
  
            }catch(err){
                ctx.response.status = 200;
                ctx.response.body = {
                    success: false,
                    msg: err.toString()
                };
            }
        }
    }
    

And this is the route function where i retrieve this array, with the external variable above it :


let adressesFound:any = [];

const getPanier = async(ctx:any) => {

        try{
    
            
            const adressValidation = await ctx.cookies.get('adressValidation');
            
            
                console.log('adressesFound : ' + adressesFound); // Retrieved variable array

                if(adressValidation === 'true'){ 
                    console.log(' -- WrittenAdress = true ');
                    console.log(' -- adressValidationCookie : ' + adressValidation);
                    ctx.render('./OBV/panier/Panier.ejs',{labels: labelProduitsArray,quantity: quantityProduitsArray,prices: prixProduitsArray,Voyant: true, UserIdPanier: userId, deletePanier: false, adressesFound: adressesFound, writtenAdress: 'true'});
                   }else{
                    console.log(' -- WrittenAdress = false ');
                    console.log(' -- adressValidationCookie : ' + adressValidation);
                    ctx.render('./OBV/panier/Panier.ejs',{labels: labelProduitsArray,quantity: quantityProduitsArray,prices: prixProduitsArray,Voyant: true, UserIdPanier: userId, deletePanier: false, adressesFound: null, writtenAdress: 'false'}); 
                   }
           
                   
            
            ctx.cookies.set('activePage','panier');
            ctx.cookies.delete('adressValidation');
        }catch(err){
    
            ctx.response.status = 200;
            ctx.response.body = {
                    success: false,
                    msg: err.toString()
                }
        }
        
    
    }

Finally this is the log i get where we can see that redirection is fired before shipEngine function finish running

First log result

when i reload the page or do a get request with the same url (same effect), so route function getPanier is running again, now i get some data from the array variable, proving redirection is fired before the variable array has the time to be filled ( i suppose ) :

Second Log result after manually reloading the page

How can i avoid this behaviour, i naturally thinked about promises but how do i implement it ? ans why await is not working here ?

0

There are 0 best solutions below