简体   繁体   中英

Can someone explain this recursive function MongooseJS

I have had a look at this function.

I can see that it generates a slug, but I dont quite understand how it works. On line 327 it returns the promise from the Model.findOne function, but inside the callback of that Model.findOne function, they recursively call the outer function that starts at line 321 again.

Can anyone help me? I need to generate some unique slugs as well, and this seems like a solution - if I can understand it.

checkIfSlugExists function in your example ensures that there is no documents with slugToFind slug in database already.

checkIfSlugExists not simply checks that the slug if vacant, but it also has some failover mechanisms. So, in the end it returns a promise to a vacant slug:

  1. If slugToFind don't exist in database, then it's returned (line 331 ).
  2. Otherwise checkIfSlugExists checks for a longSlug (lines 338-341 ), which is just a longer version of the original slugToFind .
  3. If both slugToFind and longSlug are already taken, then checkIfSlugExists starts adding numbers to longSlug (line 344-355 ), starting from 2, untill it finds a vacant slug.

Every time checkIfSlugExists wants to check for some new slug it recursively calls itself with this new value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM