I spent a good couple hours troubleshooting a bug where the yelp-fusion api said I was sending too many requests per second, so I finally found a way to delay each api request to make it work. Please take a look at the code and give me any tips you have. I’d like to see how this could be done in a better way if possible.
Here is my server.js where post requests come through:
//handle post requests for getting yelp data app.post('/post', async function(req, res) { let yelpInData = [] let result = null; req.body.forEach((item) => { yelpInData.push(item); }); result = await handleYelp(yelpInData); //send data back to the front end res.send(result); }); //handle yelp api async function handleYelp(yelpInData) { let yelpData = []; for (let i = 0, len = yelpInData.length; i < len; i++) { let result = await searchPlace(yelpInData[i]); yelpData.push(result); } // console.log(yelpData); return yelpData; } function searchPlace(city) { //console.log(city) return new Promise((resolve) => { setTimeout(() => { let coords = city.coords.lat + "," + city.coords.lng; let name = city.name; client.search({term: name, location: coords}).then(response => { //name, img url, review count, rating, price, location.display address, is closed,phone resolve({ name: response.jsonBody.businesses[0].name, img: response.jsonBody.businesses[0].image_url, hours: response.jsonBody.businesses[0].is_closed, revcount: response.jsonBody.businesses[0].review_count, rating: response.jsonBody.businesses[0].rating, price: response.jsonBody.businesses[0].price, location: response.jsonBody.businesses[0].location.display_address.toString(), phone: response.jsonBody.businesses[0].display_phone, url: response.jsonBody.businesses[0].url }); }).catch(e => { console.log(e); }); }, 100); }) }
Is setTimeout a good idea for delaying the api requests to yelp or is there a different way to delay? Here is the git repo if you want to run the web app: https://github.com/capozzic1/knockout_map