J
I'm not very clear what's missing you from behavior, so let's analyze it step by step:1 !async function() {
You declare an anonymous function that will return a promise2 let arrayNumbers = [1, 2, 3, 4, 5];
3 let numbersToFind = [7, 4, 5];
Okay, we have two normal arrays with numbers...4 let result = arrayNumbers.filter(async e => {
Uh-oh, first rare thing: the filter method allows filtering the elements of an array. To do so, use the function you pass as a parameter and call it for each element of the array. If the function returns trueHe stays with the element and if he doesn't rule it out. Why did I put true in italics? Well, because for Javascript any value that is not null, undefined, false, 0 or an empty chain ('') can be interpreted as true:console.log("un objeto es verdadero?", !!{});By declaring the function that filters like asynchronous, it is returning a class object Promise, therefore will always be processed as verdaderoI mean, we're not leaking anything, as we'll see later.5 console.log('inside filter')
In every filter iteration, we write a text, nothing special here... but it is good to emphasize that it is clearly seen that promises are intended to be fulfilled immediately and in this case it is achieved because there is nothing to expect.6 let found = await numbersToFind.find( a => {
7 return a === e;
8 });
Here to use await It doesn't contribute anything, it's a non-synchronous function, but it causes the resolution to stay "on hold," causing other logs to be displayed before.let asyncFn = async () => {
let array= [1,2,3,4];
let found = await array.find(e=> e===3);
console.log('1',found);
};
let asyncFn2 = async () => {
let array= [1,2,3,4];
let found = array.find(e=> e===3);
console.log('2',found);
};
asyncFn()
asyncFn2()9 console.log('down found');
10 if(found) {
11 console.log(found);
12 console.log('dentro de encontrado')
13 return e;
14 }
15 });
16 console.log('outside functions');
17 console.log(result);
18}();
The rest of the code has nothing special, it shows the data expected.Now imagine that we have to filter values from an array and the result depends on an AJAX call, for example. How could we do that? Well in two steps:async function esPar(n) {
return n%2 ===0;
}
//Simplemente probamos que funciona
esPar(3).then(resultado => {
console.log('El número 3 es par?', resultado);
});
let array = [1,2,3,4];
//guardamos el resultado de aplicar la función esPar a cada elemento
let resultadosP = array.map(esPar);
console.log('Promesas!', resultadosP.toString());
Promise.all(resultadosP).then(resultados => {
//Nos quedamos con los elementos donde esPar devolvió "true"
let filtrados = array.filter((elem,indice) => {
return resultados[indice];
});
console.log(filtrados);
});