My URL Shortener is always saving to the same short_url

Tell us what’s happening:
I cannot seem to get the url shortener to increment. I’m running it as a while loop, where it checks if there is a record with short_url: i(starts at 0), if there isn’t, it puts this record there. if there is, it increments the i variable and tests again, basically putting them in sequentially.

This is not how it is happening though. I’ll attach 2 excerpts from my code as well as the repl.

Your code so far
definition of functions

  console.log(number)
  await URL.findOne({short_url: number}, (err, user)=>{
    if (err){
      return 'err'
    }
    if(user){
      return true;
    }else{
      return false;
    }
  });
}

within the post request
```

let i = 0

let hasurl = true
while(hasurl === true){
  console.log('incrememnting')
//is there a record of this number?
  hasurl = findByAsync(i)
  i++
  
}

//Then assign that number to the URL by creating a new record with the url and the number
//this is supposed to make the url in database and save it with a number, currently not working? do i put done in?

createAndSaveUrl(req.body.url,i)


repl link: https://repl.it/@SethAlan/boilerplate-project-urlshortener#server.js


**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36</code>.

**Challenge:** URL Shortener Microservice

**Link to the challenge:**
https://www.freecodecamp.org/learn/apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice

Not sure why my code blocks look so ugly in the above example.
Sorry about that!

That’s because your code doesn’t wait for findByAsync(i) to return - it just assigns pending promise to hasurl (making it fail while check), increments i to 1 and exits while loop.

1 Like

Ok, that makse some sense, is there away to make it wait while I run the while loop? or should I try and do it a different way (i.e. finding the max value for short_url, then increasing it by 1)

Make the function async and await for findByAsync to return.

I’m sorry, which function? Could you show me at least in psuedocode ? (i’ve been helplessly googling stuff and now I’m somehow more lost)

app.post('/api/shorturl/new', async (req, res)=>{
                              ^^^^^
  ...
  ... await findByAsync()
      ^^^^^

Oh! The whole thing needs to be asynchronous! That makes much more sense