DevDavid
DevDavid

Reputation: 325

Node.js: Returning value from function with async call inside

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

Upvotes: 1

Views: 2097

Answers (1)

MightyMouse
MightyMouse

Reputation: 13818

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
});

Upvotes: 2

Related Questions