I am trying to create a route that makes 2 API calls, the second depends on the results from the first one and only needs to be called if certain criteria are met. Below are the problems I am having.
- The finalCheck function seems to get called before the forEach no matter what? Even when wrapped in the if statement
- The counter and userNamesAvailable are not available out of the scope they are assigned in.
I am sure there is a better way to do this and would love any relevant advice.
router.post('/namecheck', async function(req, res, next) { var name = req.body.name; var counter = 0 var domains = [] var userNamesAvailable = [] var dotcom = true var answer = '' getDomains(checkDomains) // Check domain availabilty function getDomains (callback) { var url='https://api.ote-godaddy.com/v1/domains/available?checkType=FAST' Unirest.post(url) .headers({ "Authorization" : "sso-key ", "Content-Type": "application/json" }) .send( [ name + '.com', name + '.net', name + '.org' ] ) .end(function(response) { domains=response.body.domains console.log(domains) callback(domains) }) } function checkDomains(domains) { var d = 0 //If no data is returned send error if(!domains) { console.log("No data returned") return next("No data returned") } else { //Check how many domains are unavailable for(var i=0; i < domains.length; i++) { if(domains[i].available == false){ d = d + 1 //Flag if the .com is available if(domains[i].domain == name + '.com') { dotcom = false } } } if (d >2) { console.log("d is greater than 1") answer = 'no' //If 2 domains are available and one is .com continue } else if (d>1 && dotcom =='false') { answer = 'no' } } getUsernames(finalCheck) } function getUsernames(callback){ // Social Sites to Check var sitenames = [ 'facebook', 'twitter', 'instagram', 'youtube', 'slack', 'blogger' ] // Check Usename availabitliy let i = 0 sitenames.forEach(sitename => { Unirest.post('https://api.namechk.com/services/check.json') .headers({ 'AUTHORIZATION': 'Bearer ', 'Accept': 'application/vnd.api.v1+json', }).send({ 'site': sitename, username: name, }).end(function(response) { if(response.body.available == false){ counter ++ } else { userNamesAvailable.push(response.body) } }); i++ }); console.log(counter) console.log(userNamesAvailable) if(i == sitenames.length){ callback(counter, dotcom) } } function finalCheck(counter, dotcom) { console.log('Start finalCheck') console.log(counter) console.log(dotcom) //Final Check for is a name is a go or not //If one social site is not available and the if(counter == 1 && dotcom =='true') { console.log(5-counter + ' social sites available') res.send("yes"); } else { res.send("no") } } })
d > 1 & dotcom == 'false'and perhaps you meantd > 1 && dotcom == false(ie, change & to && and change 'false' to false). Same changes for finalCheck.getUsernameshappens before theforEachbecause each of those elements creates an asyncronous call. You need to watch that all of those requests end before calling the callback.