get products with metafields by the collection_id ONLY JS

moyanoa
Excursionist
29 2 5

Hello everyone I am making an ajax call to download a json, on which I have to work, in the .done, I assign it to a global variable (the one I use to work on it later);

The issue that obviously when I want to continue working with it, it is still not assigned and throws an undefined error ...

The issue that I cannot use async false, since there are several calls and it takes too long, what would be an alternative?

Thanks

 

Sin título.png

Reply 1 (1)

Not applicable

Could you not do something like this?

 

 

var sortedProducts = await loadJSONcollection('/collection.json');

function loadJSONcollection(JSONurl){
  //$.ajax returns a promise
   return $.ajax({
      url: JSONurl,
      type: 'GET',
      success: function(res){
        sortedProducts = $.parseJSON(data);
    
      },
      error: function(){
 	//fail
      }
    })
}

 

 

 

Or maybe sortedProducts is not truly global. 

 

 

 

this.sortedProducts = {};

function loadJSONcollection(JSONurl){
  //use self to access this 
 const self = this; 
    $.ajax({
      url: JSONurl,
      type: 'GET',
      success: function(res){
        sortedProducts = $.parseJSON(data);
        //setting our global in a callback 
       self.sortedProducts = sortedProducts;
      },
      error: function(){
 	//fail
      }
    })
  
}