title: Node.js: Returning value from function with async call inside
body: <p>I'm trying to create a synchronous function which creates a random string and checks if there's already a file with that name on Amazon Web Service S3. How could I make the function synchronous as inside of it is the asynchronous web service call to AWS? If the filename already exists, the function should call itself again (recursive) until a available filename is found.</p>
  
  <pre><code>var generateUniqueAWSKey = function(prefix) {
      var unique = generateRandomString(); // generates a random string
      var name = prefix + unique + '.png';
      awss3.headObject({ Bucket: 'pics', Key: name }, function(error, result) {
          if (!error) {
              unique = generateUniqueAWSKey(prefix);
          }
      });
  
      return unique;
  };
  
  var filename = generateUniqueAWSKey('prefix_');
  // more code below using the filename
  </code></pre>