JSFiddle - React, Tailwind, and code Playground

by duffn

JavaScript

function showAll(results) {
	console.log('All done, time for doing something else with results')
	console.log(results)
}

function checkName(person) {
    console.log('checking name of ' + person.name)
    if (person.name === 'Julie') return true 
}

function checkPersons() {
		// Do something here to get new data from an external source
    var data = {
    	// 'goAgain': https://newUrl.com,
    	'results': [
        {name: 'Bob', age: 21},
        {name: 'Frank', age: 15, go: 1},
        {name: 'Julie', age: 12}
    	]
    }
    
    var persons = data.results
    var results = []
    
    persons.forEach(function(person, i) {
        if (person.age >= 18) {
            console.log('do not need to check name of ' + person.name)
            results.push(person)
        } else {
            setTimeout(function() {
                if (checkName(person)) {
                    console.log('Julie is ' + person.name)
                    results.push(person)
                }
            }, 5000 * i)
        }        
    })
    
    if (data.goAgain) {
    	// Go back and call the function again to get the 
      // next set of results from external source
      // checkPersons(goAgain)
    	console.log('Calling the function again to get more results if necessary')
    } else {
    	// But, checkName is still running because of setTimeout
      // so results doesn't yet have everything we need
    	showAll(results)
    }
}

checkPersons('https://someurl.com')