1

I have the below function which correctly takes from the response the prefix and the suffix of the image and makes a variable result,which holds the url of the venue image. However when i return the result, i keep having undefined.What is going wrong here?

function getPhotoUrl(venue_id,venue_location,venue_query){
  request({
      url: 'https://api.foursquare.com/v2/venues/'+venue_id+'/photos',
      json:true,
      method: 'GET',
      qs: {
        client_id: 'my_id',
        client_secret: 'my_secret',
        near:venue_location,
        query: venue_query,
        v: '20171114',
        limit: 1
      }
    }, function(err, res, body) {
        var result="";
        if (err) {
          console.error(err);
        } else {
          console.log(body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix);      
      }
      result=body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix;
      return result; 
    }
  );
}
<!-- begin snippet: js hide: false console: true babel: false -->
Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36

1 Answers1

0

Try using async / await. Wrap your execution in a Promise to resolve the return value and reject the error value. This way you can just await on the function and get the return value. Keep in mind await stops the execution until the returned promise is fulfilled.

function getPhotoUrl(venue_id,venue_location,venue_query){
  return new Promise((resolve, reject) => {
    request({
      url: 'https://api.foursquare.com/v2/venues/'+venue_id+'/photos',
      json:true,
      method: 'GET',
      qs: {
        client_id: 'my_id',
        client_secret: 'my_secret',
        near:venue_location,
        query: venue_query,
        v: '20171114',
        limit: 1
      }
    }, function(err, res, body) {
        var result="";
        if (err)
          reject(err);     
      }
      result=body.response.photos.items[0].prefix+"300x500"+body.response.photos.items[0].suffix;
      resolve(result);
    });
  })
}

await getPhotoUrl('', '', '')
Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36