简体   繁体   中英

While Loop for Database look up

We've designed our site so that we can use a blog's slug to get its content, for example www.mysite.com/blog/blog_1

'blog_1' being the slug (I know I'm insulting your intelligence).

That slug is determined with this simple method:

let slug = blog.title.toLowerCase().split(' ').join('-')

So something like 'This is my blog title' would be 'this-is-my-blog-title'.

However, we can't have duplicate slugs. Therefore I tried this:

let slug = blog.title.toLowerCase().split(' ').join('-')
let i

do {
  slug += i
  i++
}
while (await Blog.find({ slug })

However, it seems to hang up. Can you even use await inside a while loop? I just want to increment the slug name by one until the database call returns null at which point I can use that slug for the blog.

Any ideas?!

Thank you!

Yes you can use await in do..while loops. For example:

 async function test(i) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(i < 10) }, 1000) }) } async function main () { let i = 0 do { console.log(i) i++ } while (await test(i)) } main()

You should first correct some minor errors, such as let i = 0 instead of just let i , and there is a missing parenthesis at the end of your code.

If it still does not work, you should probably check your function Blog.find()

you can use for of with await

let counter= [0];
let slug;
for( let i of counter){
  slug+=i; 
  let result = await Blog.find({ slug })
  if(result){
    counter.push(i+=1)
  }
}

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