1

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.

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

1 Answer 1

2

You need to start thinking in terms of callbacks. I am not sure which condition should call the same function again, but your logic should be there on the callback function of the asynchronous call that you are making. In other words, your code should look like this:

function generateUniqueAWSKey (prefix, callback) {
    var unique = generateRandomString(); // generates a random string
    var name = prefix + unique + '.png';
    awss3.headObject({ Bucket: 'pics', Key: name }, function(error, result) {
        if (error) {
            // error handling here
            return generateUniqueAWSKey(prefix, callback); // say you do recursion here
        }
        else {
            return callback(unique); // no need for recursion; return result 
        }
    });
};

generateUniqueAWSKey('prefix_', function (name) {
    var filename = name;
    // more code below using the filename
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.