javascript - Promised recursive function does not trigger return statement -


i'm trying write "slug validator" querying database if wanted slugged string available.

for use un reccursive function increments number , test concatenated slugged string.

example :

  • i want insert my-slugged-string in database. want check if my-slugged-string available (not used).
  • i query database my-slugged-string , if exists, tries again my-slugged-string1, , if exists tries again my-slugged-string2, etc...
  • if my-slugged-stringx not exists, return value.

first of all, here code

import nodegremlin 'gremlin'; import gremlin 'gremlin-template-string';  import slug 'slug';  import promise 'bluebird';   let client = nodegremlin.createclient(8182, 'localhost'); client = promise.promisifyall(client);   module.exports.generatenew = function (label, stringtoslug) {     let sluggedstring = slug(stringtoslug, {lower: true});     return findavailable(label, sluggedstring); }  function findavailable(label, stringtotest, = ''){     const mixedstring = stringtotest + i;     let query = `g.v().has(label, '${label}').has('slug', '${mixedstring}')`;     return client.executeasync(query)         .then((item) => {             if (item[0]){                 if (i === '') = 0;                 return findavailable(label, stringtotest, ++i);             }             // breakpoint             console.log(mixedstring);             return mixedstring;          })         .catch((err) => {             // manage error         }); } 

and i'm calling code

import * slug './slug'; import promise 'bluebird';  let slug = promise.promisifyall(slug);  export function create(item = {}, callback) {     // [...]     slug.generatenewasync('item', 'my string slug , test')         .then((sluggedstring)=>{             //bla bla bla         })     // [...] } 

my problem that, if breakpoint reached (the algorithm works, have test : can console.log right value), nothing returned , process won't stop , keep runing eeeveeer... until timeout comes ! :) :) :)

i'm missing on javascript promises principle.

i'd appriciate guys ;)

edit : @adam, code edited

yes, nothing returned because there no return statement in findavailable! add here:

function findavailable(label, stringtotest, = ''){     const mixedstring = stringtotest + i;     let query = `g.v().has(label, '${label}').has('slug', '${mixedstring}')`;     return client.executeasync(query) //  ^^^^^^         .then(…); } 

that said, module you've written return promise now. there no need promisify - in fact, won't work promisification doesn't take callback. don't call promisifyall on it, don't use async suffix method call:

… export function create(item = {}, callback) {     …     return slug.generatenew('item', 'my string slug , test') //              ^^^^^^^^^^^         .then((sluggedstring)=>{             …          }); } 

Comments