0

I have the following which is running thru a loop going over the response from a returned JSON result.

I am able to push all of this data into my object product.variations with no problems. The product.variations.quantity however will not return the string data from the function that I have associated. The function that is attached getProductStock is called ok but it comes in as undefined when I attempt to return the data back into the key that will be pushed.

The reason I am confused is because when I run a console.log callback function I can see the string data appearing with no problem.

The issue is that it will not return into the quantity key and then push back into my main object product. Keeps returning undefined.

Any help would be greatly appreciate :)

   product.variations.push({
               'identifier' :  dataJSON.msg[z].sku,
               'size' : dataJSON.msg[z].size,
               'quantity' : getProductStock(token, dataJSON.msg[z].sku, function(stockLevel){
                 console.log(stockLevel);
                 return stockLevel;
               })
             });

Then later on I have the function that is getting called 'getProductStock'

function getProductStock(token, goods_sn, callback){
  var post_data = "token=" + token + "&goods_sn=" + goods_sn;
  var api_url = 'https://randomapiurl.com/getStock?';

  var options = {
    method: 'POST',
    url: api_url,
    data: post_data
  };

  curl.request(options, function(err,data){
    var JSON_result = JSON.parse(data);
        JSON_result.msg.page_result.forEach(function(data, index){
          callback(data.goods_number);
        });
  });

}
jremi
  • 2,593
  • 2
  • 22
  • 31
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – gyre Mar 09 '17 at 16:59

1 Answers1

0

     
function getProductStock(token, goods_sn, callback){
  var post_data = "token=" + token + "&goods_sn=" + goods_sn;
  var api_url = 'https://randomapiurl.com/getStock?';

  var options = {
    method: 'POST',
    url: api_url,
    data: post_data
  };

  curl.request(options, function(err,data){
    var JSON_result = JSON.parse(data);
        JSON_result.msg.page_result.forEach(function(data, index){
          pushData(data.goods_number);
        });
  });

}
function pushData(quantity)
{

  product.variations.push({
               'identifier' :  dataJSON.msg[z].sku,
               'size' : dataJSON.msg[z].size,
               'quantity' : quantity
           });
           
 }     
funcoding
  • 663
  • 5
  • 9