Saturday 11 March 2017

Issue with forEach loop over array performing HTTP POST request on each object

I am using npm request module to perform super basic POST request against an API to upload image urls and get a new url link for each object within the array of urls. Once I have them I will push them back into my array.

I can't seem to make this work. I can get it working fine when I perform it over a regular string , but when I attempt to loop the http POST request over the array I cant get it to return.

I have an array for example:

var product = {
      extra_images:
        [ 'https://some.imgcdn.com/myimage1.jpg',
        'https://some.imgcdn.com/myimage2.jpg',
        'https://some.imgcdn.com/myimage3.jpg' ]
    }

product.extra_images.forEach(function(originURL, index){
          urlCloaker(originURL, extraImgResponse);
        });

Here is the function that performs the request to the API:

function urlCloaker(imgUrl, cloakedURLResponse){

  var imgUrl = 'upload=' + imgUrl;

  request('http://coolsite.com/api?' + imgUrl, function (error, response, body) {
      if(error){
        return console.log('Error:', error);
      }

      if(response.statusCode !== 200){
        return console.log('Invalid Status Code Returned:', response.statusCode);
      }
      else {
        var JSON_result = JSON.parse(body);
        cloakedURLResponse(error, JSON_result.data.img_url);
      }
  });
}

Here is my callback:

 function extraImgResponse(err, data){
      if(err)
        console.log("ERROR: " , err);
      else {
        product.extra_images.push(data);
      }

    }



via jremi

No comments:

Post a Comment