Promise help/ayuda

Me gustaría saber como conseguir que funcione el if === 7 porque no me funciona, directamente salta el .catch. Y quiero que salte el .then. Porque no funciona si el bucle for está bien definido?

También quiero imprimir por consola la frase resultante cortada. He sido capaz de mostrar el numero de palabra con ${i + 1} y la palabra limitante con ${array[i]. Pero como muestro la frase cortada completamente hasta la palabra limitante?

Gracias!

let array = ['A', 'veces', 'me', 'cuesta', 'ver', 'las', 'cosas', 'del', 'mismo', 'modo', 'que', 'tú.'];

let variable = new Promise(function(resolve, reject){
  for(let i = 0; i < array.length; i++){
    array[i];
    if(i === 7){
      resolve(`Ha llegado al número máximo de palabras que mostrar (${i + 1})! La palabra límite es "${array[i]}" y el resultado de la frase completa, cortada, será: ...`);
    } else {
      reject('El bucle for da problemas y no ha funcionado el corte de la frase');
    }
  } 
});

variable
  .then(cortada => console.log(cortada))
  .catch(error => console.log(error));

I’m very confused by this code.

What is it trying to do? What do you want the output to be for a given input?

If I understand what you are trying to do, you shouldn’t need a loop for this. You also shouldn’t need a Promise, but I understand if you want to do it as a learning exercise. But there should be no need for a loop to figure out how large an array is.


What is this line trying to do?

array[i];

Me gustaría saber como conseguir que funcione el if === 7 porque no me funciona, directamente salta el .catch.

That’s not what I’m seeing. Put in some log statements. It seems to me to run through them all before rejecting.

Hi @kevinSmith
Si, es un código de entrenamiento para practicar las promesas.
Me he inventado el array “array” y quiero que, cuando el bucle for consiga la posicion número 7, muestre las strings 0, 1, 2, 3, 4, 5, 6 y 7.(a, veces, me , cuesta, ver , las, cosas, del).
Las que tengan posicion 8, 9, 10…etc, no quiero mostrarlas. Es eso lo que quiero hacer. Cortar la frase por el índice nº7.
Iba a hacer una promesa mas sencilla pero tenia ganas de complicarla un poco más.

Eso es lo importante.

La 2a cosa que quería, era que, en resolve, mostrar Ha llegado al número máximo de palabras que mostrar (${i + 1})! La palabra límite es "${array[i]}" y el resultado de la frase completa, cortada, será: ...
Y al final de la frase, mostrar la frase cortada. El resultado, de corte de la frase.
Así: Ha llegado al número máximo de palabras que mostrar (${i + 1})! La palabra límite es "${array[i]}" y el resultado de la frase completa, cortada, será: A, veces, me , cuesta, ver , las, cosas, del

El problema creo, que algo he hecho mal, porque solo funciona el .catch o reject.
El .then o resolve no me funciona.

Looking at it, one thing that strikes me is that you are calling resolve and reject multiple times. I think one of the rules of Promises is that they can only resolve or reject once. I think a better approach might be to figure out what you want to do, and then resolve or reject.

I’m still not sure why you need a loop. Can’t you check the length of the array?

1 Like

Not an expert but this is just another opinion. I get that you just want to get familiar with the syntax, which is a good approach to get started.

  • As someone commented, normally you resolve or reject, and that’s the end of the story.
  • If we loop without return values, it will always run through the loop till the end, so you could return in that step (the last value in your code is probably the last reject).
  • If we return a value in both fns, then it will run only once.

So we could move the reject off the loop. A similar example:

let array = ['A', 'veces', 'me', 'cuesta', 'ver', 'las', 'cosas', 'del', 'mismo', 'modo', 'que', 'tú.'];

let isVecesHere = new Promise(function(resolve, reject){
  for(let i = 0; i < array.length; i++){
   console.log(array[i]);
    if(array[i]==='veces'){
      return resolve('found veces');
    } } 
      return reject("didn't find veces");
});

isVecesHere
  .then(cortada => console.log(cortada))
  .catch(error => console.log(error));

Also shorter:


let isVecesHere = new Promise(function(resolve, reject){
  array.forEach(word=>{ 
if(word==='veces'){ 
return resolve('found veces')
    }}) 
      return reject("didn't find veces");
});
1 Like

@kevinSmith no pasa nada, solo quería aprender a manejar las Promesas, aunque el ejercicio no tenga sentido. Lo he hecho tan raro, que es muy dificil encontrarle el sentido. Me conformo con el ejemplo de @anon22924398 y sigo probando más Promesas y practicando.
Es una buena forma la de santimir, de encontrar una palabra dentro del array, que se podria hacer con otro método, pero está muy bien para practicar promesas así.
Gracias a los dos!

1 Like