I have an ajax function that looks for the code of all the companies and goes in the other ajax function to look for the employees.
In order for the page to not crash when doing this search I'm using the async: true
attribute, but in doing so, I can not return the data on the same page working using console.log()
Follow my code for review
$( document ).ready( function(){
empresas()
} )
let empresasArr = {
"empresa":[
{
"nome": "Digiboard",
"id": 1
},
{
"nome": "HAM",
"id": 2
}
]
}
let dadosArr = {
"dados": [
{"nome": "Carlos", "empresa": 1},
{"nome": "Vicente", "empresa": 2},
{"nome": "Maiza", "empresa": 2},
{"nome": "Charles", "empresa": 1},
{"nome": "Michel", "empresa": 2}
]
}
function empresas(){
$.ajax({
url: 'https://api.myjson.com/bins/b0c22',
type: 'post',
dataType: 'json',
async: false,
}).done( function( d ){
var retorno = "";
let string = ""
console.log( d )
$.each( d.empresa, function(i, j){
console.log( j.nome )
retorno = fnNomes( j.id, function( retorno ){
//console.log( retorno )
string =+ retorno
} )
})
console.log( string )
$('.retorno').append(string)
})
}
function fnNomes( id, cb ){
let nomes = "";
$.ajax({
url: 'https://api.myjson.com/bins/1cksbu',
type: 'POST',
async: true,
dataType: 'json',
data: { empresa : id }
}).done( function( d ){
console.log( d )
$.each( d.dados, function(i, j ){
if( j.empresa == id ){
nomes += j.nome+"<br>"
}
})
cb( nomes )
} )
// console.log(nomes);
return nomes
}
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<div class="retorno"></div>
The Company.json
{
"empresa":[
{
"nome": "Digiboard",
"id": 1
},
{
"nome": "HAM",
"id": 2
}
]
}
The data
"dados": [
{"nome": "Carlos", "empresa": 1},
{"nome": "Vicente", "empresa": 2},
{"nome": "Maiza", "empresa": 2},
{"nome": "Charles", "empresa": 1},
{"nome": "Michel", "empresa": 2}
]
I heard about such a deferred and promised, would not solve the problem, but I still did not understand how to use them