-2

I need to get values from function Woocommerce. So I want the values display out of the function. Is there another simple solution to solve it?

WooCommerce.get('products?per_page=100', function(err, data, res) {

  var data = JSON.parse(res);

  var id = data[0]['id'];

});

console.log(id); // output is undefined
galkin
  • 5,264
  • 3
  • 34
  • 51

1 Answers1

0

get is async, meaning that its callback is called after everything has finished.

id is not available anymore as it's scoped to the get callback function.

To help you debug, you could try:

var id;   

WooCommerce.get('products?per_page=100', function(err, data, res) {
    var data = JSON.parse(res);

    // keep the data you want in another variable, or object.
    id = data[0]['id']; 

    console.log(id); // test inside the function
});

The callback gets called when a response is received from the server.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129