0

I want to check for a slug if already exist using Javascript NodeJs, Bookshelf...

So far I have this code which is actually not working:

var makeSlug = function (slug) {
    var baseSlug = slug;
    var i = 1;
    //console.log("RETURN: " +  slug_exists(slug));
    while (slug_exists(slug)) {
        slug = baseSlug + '-' + i;
        i++;
    }
    return slug;
};

var slug_exists = function (album) {
    new Album({slug: slugify(album)})
        .fetch()
        .then(function (album) {
            if (album) {
                console.log("trueee");
                return true;
            } else {
                console.log("falseee");
                return false;
            }
        });
};

And somewhere in the code I call this function as var newSlug = makeSlug('Endless River'); It seems like slug_exists function doesnt return me true eventhou it prints "trueee", therefore while loop also doesnt work... Any suggestion, help how would you do this?

Lulzim
  • 547
  • 4
  • 9
  • 22

1 Answers1

1

You can't return like that, inside of a promise's callback (as it will be the return for that function, not the outer one).

Since you have a promise already, return that and let makeSlug() check the then().

var slug_exists = function (album) {
    return new Album({slug: slugify(album)}).fetch();
};
alex
  • 479,566
  • 201
  • 878
  • 984